﻿using CommandService;
using Entity.FrameEntity;
using Entity;
using System.Text;
using Tools;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Data;
using SysFramework;
using Entity.DbEntity;
using Entity.DbEntity.sys;
using ClosedXML.Excel;
using System.Net.Mime;
using Entity.DbEntity.Plan;
using static ClosedXML.Excel.XLPredefinedFormat;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using DocumentFormat.OpenXml.Drawing;
using System.Runtime.InteropServices;

namespace BLL
{
    public class PlanBLL : PubMethod
    {
        Commands cmd;
        ReturnResult rsl;
        OperateModel oper;
        List<OperateModel> operList;
        BarBLL bar;
        OutBaseHelper outBase;
        StringBuilder sb;
        public PlanBLL()
        {
            cmd = new Commands();
            outBase = new OutBaseHelper();
        }

        /// <summary>
        /// 生产计划列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPlanList(JObject loginUser, string pageIndex, string pageSize, ref string pageCount, string condition, string sign = null)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }

                StringBuilder sb = new StringBuilder();
                string userCode = "", isAdmin = "", roleCode = "";
                #region 人员身份信息
                //获取登录人员权限信息
                userCode = loginUser["userCode"].ToString();
                isAdmin = loginUser["isAdmin"].ToString();
                roleCode = loginUser["powerRole"].ToString();

                #endregion

                #region 检索条件
                sb.Append(" isdel=0 ");
                //if (isAdmin == "0" && !roleCode.Equals("R20221126113016"))
                //{
                //    sb.Append(" and  createuser='" + userCode + "' ");
                //}
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if ((obj.Name == "status" && json["cStatus"] != null) || obj.Name == "switch")
                            {
                                continue;
                            }
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "cStatus")
                            {
                                var sArr = obj.Value.ToString().Split(',');
                                string status = "";
                                foreach (string s in sArr)
                                {
                                    if (!string.IsNullOrWhiteSpace(s))
                                    {
                                        status += "'" + s + "',";
                                    }
                                }
                                sb.Append("status in (" + status.TrimEnd(',') + ")");
                            }
                            else if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(datetime,createtime, 20)" + " >='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {//结束时间
                                sb.Append(" convert(date,createtime, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var tableName = "V_PI_ProductPlan_info";
                if (!string.IsNullOrEmpty(sign))
                {
                    tableName = "V_ProductRecentPlan_info";//往期生产计划
                }
                var list = cmd.PageList(tableName, pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);

                if (string.IsNullOrEmpty(sign))
                {
                    //生产计划列表 判断是否需要逾期提醒
                    foreach (var s in list)
                    {
                        s.Add("remindType", "0");//0 不提醒  1即将逾期提醒  2逾期提醒

                        var days = double.Parse(s["remind"].ToString());
                        if (days > 0)
                        {
                            if (!string.IsNullOrEmpty(s["finishDate"].ToString()))
                            {
                                if (!string.IsNullOrEmpty(s["remind"].ToString()))
                                {
                                    days = int.Parse(s["remind"].ToString());
                                }
                                days = 0 - days;
                                var nowDate =System.DateTime.Parse(getNowDate());
                                var finishDate = System.DateTime.Parse(s["finishDate"].ToString());
                                var remindDate = finishDate.AddDays(days);
                                if (nowDate > finishDate)
                                {
                                    s["remindType"] = "2";  //逾期提醒
                                }
                                else if (nowDate > remindDate)
                                {
                                    s["remindType"] = "1";  //即将逾期提醒
                                }
                            }
                        }

                    }
                }


                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult DelPlan(JObject loginUser, string plCode, string status)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                #region 判断计划是否已派工(状态)
                if (status == "ps-doing")
                {
                    rsl.Message = "计划(" + plCode + ")已派工，禁止删除";
                    return rsl;
                }
                #endregion

                #region 删除方法

                #region 删除计划
                DbPlanInfo plan = new DbPlanInfo();
                plan.plCode = plCode;
                plan.delMsg = loginUser["userCode"].ToString() + " " + getNow();
                plan.isdel = 1;
                oper = new OperateModel();
                oper.Data = plan;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                #endregion

                #region 删除工序
                DbPlanGx gx = new DbPlanGx();
                gx.plCode = plCode;
                gx.delMsg = loginUser["userCode"].ToString() + " " + getNow();
                gx.isdel = 1;
                oper = new OperateModel();
                oper.Data = gx;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode";
                operList.Add(oper);
                #endregion

                #region 删除工序表单（工艺）----还没写

                #endregion

                #endregion

                rsl = cmd.MoreUpdate(operList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取U8销售数据
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="saleId"></param>
        /// <param name="saleCode"></param>
        /// <returns></returns>
        public ReturnResult getSalesInfo(JObject loginUser, string condition, string saleId, string saleCode)
        {
            rsl = new ReturnResult();
            OutBaseHelper outDb = new OutBaseHelper();
            try
            {
                if (AppSettingHelper.ReadAppSettings("ConntectERP") != "1")
                {
                    rsl.Message = "没有开启ERP同步权限";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                string orType = "";

                #region 销售订单列表
                sb.Clear();
                sb.Append("select p.cInvStd spec,Convert(decimal(18,2),d.iQuantity) number,p.cComUnitCode unit,");
                sb.Append("m.cCusCode cuCode,m.cCusName cuName,d.cSOCode erpOrder,d.cInvCode proCode,p.cInvName proName,");
                sb.Append("CONVERT(varchar(10), dPreDate, 120 ) fDate,d.AutoID,d.iRowNo rowNO,");
                sb.Append("ps.cPersonName,mc.cComUnitName,");
                sb.Append("p.cInvCCode typeCode,d.cMemo memo ,d.AutoID erpRowId,d.cDefine22,m.cMemo orderMemo ");
                //sb.Append(",c.fAvaQuantity realNum ");
                sb.Append(" from SO_SODetails d inner join Inventory p on d.cInvCode=p.cInvCode");
                sb.Append(" inner join SO_SOMain m on d.cSOCode=m.cSOCode ");
                sb.Append(" left join Person ps on m.cPersonCode=ps.cPersonCode  ");
                sb.Append(" inner join ComputationUnit mc on p.cComUnitCode=mc.cComunitCode ");
                //sb.Append("  inner join (select cInvCode,ISNULL(sum(Convert(decimal(18,2),fAvaQuantity)),0) fAvaQuantity from CurrentStock group by cInvCode) c on c.cInvCode=d.cInvCode ");
                sb.Append(" where d.cSCloser is null ");
                sb.Append(" and p.cInvName not like '%费%' ");   //销售订单可能会添加版费等东西  这不显示
                #region 检索条件
                if (!string.IsNullOrWhiteSpace(orType))
                {
                    sb.Append("and m.cSTCode in (" + orType + ")");
                }
                if (!string.IsNullOrWhiteSpace(json["sDate"].ToString()))
                {
                    sb.Append("and convert(datetime,m.dDate, 20)" + " >='" + json["sDate"].ToString() + "' ");
                }
                if (!string.IsNullOrWhiteSpace(json["eDate"].ToString()))
                {//结束时间
                    sb.Append("and convert(datetime,m.dDate, 20)" + "<= '" + json["eDate"].ToString() + "' ");
                }

                if (!string.IsNullOrWhiteSpace(json["cSOCode"].ToString()))
                {
                    sb.Append(" and  d.cSOCode  like '%" + json["cSOCode"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["customName"].ToString()))
                {
                    sb.Append(" and  m.cCusName  like '%" + json["customName"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    sb.Append(" and  d.cInvCode  like '%" + json["proCode"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append(" and  p.cInvName  like '%" + json["proName"].ToString().Trim() + "%' ");
                }
                if (!string.IsNullOrWhiteSpace(json["cPersonName"].ToString()))
                {
                    sb.Append(" and  ps.cPersonName  like '%" + json["cPersonName"].ToString().Trim() + "%' ");
                }
                #endregion

                sb.Append(" order by d.cSOCode desc");
                #endregion

                var table = outDb.getData(sb.ToString(), loginUser["baseCode"].ToString());
                var list = cmd.TableToDictionary(table);

                #region 统计创建的计划数
                table = new DataTable();
                foreach (var s in list)
                {
                    // hasPlan 判断销售订单是否创建计划
                    sb.Clear();
                    sb.Append(" select * from pi_ProductionPlan_info where isdel = 0 and erpRowId = " + s["erpRowId"]);
                    table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count > 0)
                    {
                        s["hasPlan"] = "1";//已创建计划
                        #region 创建计划数
                        var rows = table.Select("plType='P-Sale'");
                        double num = 0;
                        if (rows.Length > 0)
                        {
                            foreach (DataRow dr in rows)
                            {
                                num = num + double.Parse(dr["number"].ToString());
                            }

                        }
                        s["doNum"] = num.ToString();
                        #endregion
                    }
                    else
                    {
                        s["hasPlan"] = "0";
                        s["doNum"] = "0";
                    }
                }
                #endregion

                rsl.Data = list;
                rsl.Result = true;
                return rsl;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 获取存货工艺数据信息 (工艺编码名称)
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <param name="cuCode">客户编码</param>
        /// <returns></returns>
        public ReturnResult GetProductGyCode(string proCode, string cuCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(proCode))
                {
                    rsl.Message = "存货编码不允许为空";
                    return rsl;
                }
                DataTable gyTable = new DataTable();

                var dic = new Dictionary<string, string>();
                if (!string.IsNullOrWhiteSpace(cuCode))
                {
                    sb.Append("select top 1 g.gyCode,gyName,g.plCode from pi_ProductionPlan_process g");
                    sb.Append(" inner join pi_ProductionPlan_info p on p.plCode=g.plCode and p.isdel=0 ");
                    sb.Append(" inner join gy_ProcessStandard_info gy on gy.keyCode=g.gyCode and gy.isdel=0 ");
                    sb.Append(" where g.isdel=0 and p.proCode='" + proCode + "' and p.cuCode='" + cuCode + "'");
                    sb.Append(" order by g.id desc ");
                    gyTable = cmd.GetDataTable(sb.ToString());
                }

                //客户编码为空,根据存货或所属大类获取工艺
                if (gyTable.Rows.Count < 1)
                {
                    dic["plCode"] = "";
                    #region 根据存货编码获取工艺
                    sb.Clear();
                    sb.Append("select keyCode gyCode,gyName from gy_ProcessStandard_info ");
                    sb.Append(" where isdel=0 and relationCode='" + proCode + "'");
                    sb.Append(" group by keyCode,gyName ");
                    gyTable = cmd.GetDataTable(sb.ToString());
                    #endregion

                    #region 根据存货所属大类获取工艺
                    if (gyTable.Rows.Count < 1)
                    {
                        sb.Clear();
                        sb.Append("select distinct g.keyCode gyCode,gyName from gy_ProcessStandard_info g ");
                        sb.Append(" where g.isdel=0 and g.relationCode in (select typeCode from fun_Inventory_Info ");
                        sb.Append(" where isdel =0 and status='Y' and proCode='" + proCode + "') ");
                        //sb.Append(" order by g.id desc  ");
                        gyTable = cmd.GetDataTable(sb.ToString());
                    }
                    #endregion
                }
                else
                {
                    dic["plCode"] = gyTable.Rows[0]["plCode"].ToString();
                }
                if (gyTable.Rows.Count > 0)
                {
                    dic["gyCode"] = gyTable.Rows[0][0].ToString();
                    dic["gyName"] = gyTable.Rows[0][1].ToString();
                    rsl.Result = true;
                    rsl.Data = dic;
                }
                else
                {
                    rsl.Message = "没有工艺数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }




        /// <summary>
        /// 根据计划编码获取计划数据信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult getPlanInfoByCode(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "计划编码为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_PI_ProductPlan_info where isdel=0 and plCode='" + plCode + "'");
                var pList = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Data = pList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 有效生产工序
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult GetGongXuList(string conditions)
        {
            rsl = new ReturnResult();
            try
            {

                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode,cName,id,orderNum,cMemo,'0' MaxFlNum  from fun_CommonData_Info c ");
                sb.Append(" where isdel=0 and  cType='Gx' and cCode is not null and cCode !=''");
                sb.Append(" order by convert(decimal(10,2),orderNum)  ");
                var gxTable = cmd.GetDataTable(sb.ToString());//工序

                sb.Clear();
                sb.Append("select isNull(MaxFlNum,0) MaxFlNum,* from pi_ProductionPlan_gx where isdel=0 and plCode='" + conditions + "'");
                var pTable = cmd.GetDataTable(sb.ToString());//计划工序

                foreach (DataRow dr in pTable.Rows)
                {
                    var drs = gxTable.Select("cCode='" + dr["gxCode"].ToString() + "'");
                    drs[0]["orderNum"] = dr["gxOrder"].ToString();
                    drs[0]["MaxFlNum"] = dr["MaxFlNum"].ToString();
                }

                rsl.Data = cmd.TableToDictionary(gxTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据计划编码获取计划工序信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult getPlanGxByCode(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "计划编码为空";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_gx where isdel=0 and plCode='" + plCode + "'");
                var pList = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Data = pList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 保存生产计划
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult SaveProductPlan(string datas, string cData, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                StringBuilder sb = new StringBuilder();
                var obj = JsonConvert.DeserializeObject<JObject>(datas);
                var gxs = JsonConvert.DeserializeObject<List<JObject>>(cData);
                var plan = JsonConvert.DeserializeObject<DbPlanInfo>(datas);
       
                #region 非空判断
                if (string.IsNullOrWhiteSpace(plan.proCode))
                {
                    rsl.Message = "请选择存货";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(plan.number))
                {
                    rsl.Message = "请录入计划数量";
                    return rsl;
                }
                if (string.IsNullOrWhiteSpace(plan.bomCode))
                {
                    rsl.Message = "生产BOM不能为空";
                    return rsl;
                }
                #endregion

                if (string.IsNullOrWhiteSpace(plan.finishDate))
                {
                    rsl.Message = "计划完工日期不允许为空"; return rsl;
                }

                if (!decimal.TryParse(plan.number, out decimal targetVal06))
                {
                    rsl.Message = "请检查计划数量"; return rsl;
                }
                
                DataTable gyTable = new DataTable();
                DbPlanGx gx;
                string re_plCode = "";
                if (plan.id == null || plan.id == 0)
                {
                    #region 新建
                    if (obj.Property("plCode") != null && !string.IsNullOrWhiteSpace(obj["plCode"].ToString()))
                    {
                        re_plCode = obj["plCode"].ToString();
                    }
                    string codeLength = AppSettingHelper.ReadAppSettings("CodeLength");
                    string pCode = "";
                    if (plan.plType == "P-Sale")
                    {
                        pCode = "SO";
                    }
                    else if (plan.plType == "P-BeiHuo")
                    {
                        pCode = "PO";
                    }
                    else
                    {
                        pCode = "NP";
                    }
                    plan.isdel = 0;
                    plan.plCode = this.CreateCodeInfo(pCode, "生产计划编码", codeLength);
                    plan.createtime = getNow();
                    plan.createuser = userCode;
                    plan.status = "ps-pg-set";

                
                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);

                    #region 工序数据
                    var gxCodes = "";
                    foreach (var s in gxs)
                    {
                        gxCodes += "'" + s["cCode"].ToString() + "',";
                        gx = new DbPlanGx();
                        gx.plCode = plan.plCode;
                        gx.gxCode = s["cCode"].ToString();
                        gx.gxOrder = s["orderNum"].ToString();
                        gx.isFinish = "0";
                        gx.MaxFlNum = s["MaxFlNum"].ToString();
                        gx.createuser = userCode;
                        gx.createtime = getNow();
                        gx.isdel = 0;
                        oper = new OperateModel();
                        oper.Data = gx;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }

                    #endregion

                    #region 关联计划
                    if (!string.IsNullOrWhiteSpace(re_plCode))
                    {
                        sb.Clear();
                        sb.Append("select createuser from pi_ProductionPlan_info where plCode='" + re_plCode + "'");
                        var qpTable = cmd.GetDataTable(sb.ToString());
                        if (qpTable.Rows.Count > 0)
                        {
                            sb.Clear();
                            sb.Append("select * from pi_ProductionPlan_gy where isdel=0 and plCode='"+ re_plCode + "'");
                            sb.Append(" and gxCode in (" + gxCodes.TrimEnd(',') + ")");
                            sb.Append(" and createuser='" + qpTable.Rows[0]["createuser"].ToString() + "'");
                            var table = cmd.GetDataTable(sb.ToString());
                            DbPlanTechnology gy;
                            if (table.Rows.Count > 0)
                            {
                                foreach (DataRow dr in table.Rows)
                                {
                                    gy = new DbPlanTechnology();
                                    gy.plCode = plan.plCode;
                                    gy.gxCode = dr["gxCode"].ToString();
                                    gy.id = Guid.NewGuid().ToString().Replace("-", "");
                                    gy.fieldCode = dr["fieldCode"].ToString();
                                    gy.fieldValue = dr["fieldValue"].ToString();
                                    gy.createtime = getNow();
                                    gy.createuser = userCode;
                                    gy.isdel = 0;
                                    oper = new OperateModel();
                                    oper.Data = gy;
                                    oper.Types = OperateModel.OperateType.Add;
                                    operList.Add(oper);
                                }
                            }
                        }
                    }
                    #endregion

                    #region 计划图纸 （查找相同存货 上一个计划的图纸）
                    sb.Clear();
                    sb.Append("select * from sys_upload_files where isdel=0 and businessType='Plan' ");
                    sb.Append("and businessID in (select top 1 plCode from pi_ProductionPlan_info where isdel=0  ");
                    sb.Append("and proCode='"+plan.proCode+"' order by id desc)");
                    var  fTable = cmd.GetDataTable(sb.ToString());

                    DbuploadFiles upFile;
                    foreach (DataRow dr in fTable.Rows)
                    {
                        upFile = new DbuploadFiles();
                        upFile.businessType = dr["businessType"].ToString();
                        upFile.fileName = dr["fileName"].ToString();
                        upFile.businessID = plan.plCode;
                        upFile.filePath = dr["filePath"].ToString();
                        upFile.isDel = 0;
                        upFile.createtime = getNow();
                        upFile.createuser = userCode;
                        oper = new OperateModel();
                        oper.Data = upFile;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }

                    #endregion 

                    #endregion
                }
                else
                {
                    #region 修改
                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id,plCode";
                    operList.Add(oper);
                    #endregion

                    sb.Append("select * from pi_ProductionPlan_gx where isdel=0 and plCode='" + plan.plCode + "'");
                    var gxTable = cmd.GetDataTable(sb.ToString());

                    #region 工序数据
                    #region 删除（计划的全删）
                    gx = new DbPlanGx();
                    gx.plCode = plan.plCode;
                    gx.isdel = 1;
                    gx.delMsg = getNow() + "  " + userCode;
                    oper = new OperateModel();
                    oper.Data = gx;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";
                    operList.Add(oper);
                    #endregion
                    #region 添加
                    foreach (var s in gxs)
                    {
                        gx = new DbPlanGx();
                        gx.plCode = plan.plCode;
                        gx.gxCode = s["cCode"].ToString();
                        gx.gxOrder = s["orderNum"].ToString();
                        gx.isFinish = "0";
                        gx.MaxFlNum = s["MaxFlNum"].ToString();
                        gx.createuser = userCode;
                        gx.createtime = getNow();
                        gx.isdel = 0;
                        oper = new OperateModel();
                        oper.Data = gx;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }
                    #endregion
                    #endregion
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有保存数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取计划生产工艺
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gyCode">工艺编码</param>
        /// <returns></returns>
        public ReturnResult GetPlanProcess(string plCode, string gyCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(plCode) && !string.IsNullOrWhiteSpace(gyCode))
                {
                    sb.Append("select top 1 relationCode proCode,relationName proName,gyName,versionCode,memo,keyCode gyCode ");
                    sb.Append("from gy_ProcessStandard_info where keyCode='" + gyCode + "' and isdel=0");
                }
                else
                {
                    sb.Append(" select top 1 p.proCode,p.proName,s.gyName,s.versionCode,s.memo,p.gyCode from  V_PI_ProductPlan_info p");
                    sb.Append(" inner join gy_ProcessStandard_info s on s.keyCode = p.gyCode");
                    sb.Append(" where p.plCode='" + plCode + "' ");
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取计划关联工序
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult GetPlanGx(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select cCode, cName, cValues, pgx.gxOrder ");
                sb.Append("from fun_CommonData_Info c ");
                sb.Append("inner join pi_ProductionPlan_gx pgx on pgx.gxCode = c.cCode and pgx.isdel = 0 and plCode = '"+plCode+"' ");
                sb.Append("where c.isdel = 0 and cType = 'gx' ");
                sb.Append("order by pgx.gxOrder asc ");
                var table = cmd.GetDataTable(sb.ToString());

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 加载计划工序工艺表单
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult loadPlanGxForm(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                List<Dictionary<string, object>> dlist = new List<Dictionary<string, object>>();
                var obj = JsonConvert.DeserializeObject<JObject>(datas);
                StringBuilder sb = new StringBuilder();
                if (!string.IsNullOrWhiteSpace(obj["plCode"].ToString()))
                {
                    sb.Append("select * from pi_ProductionPlan_process where isdel=0");
                    sb.Append(" and gxCode='" + obj["gxCode"].ToString() + "' and plCode='" + obj["plCode"].ToString() + "'");
                    sb.Append(" order by groupCode,fieldOrder asc");
                }
                else
                {
                    sb.Append("select * from fun_ProcessTechnology_form  ");
                    sb.Append("where gxCode='" + obj["gxCode"].ToString() + "' and isdel=0");
                    sb.Append(" order by groupCode,fieldOrder asc");
                }
                var table = cmd.GetDataTable(sb.ToString());
                string groupCode = "";
                List<string> reList = new List<string>();
                foreach (DataRow r in table.Rows)
                {

                    if (!reList.Contains(r["groupCode"].ToString()))
                    {
                        var dic = new Dictionary<string, object>();
                        dic["gCode"] = r["groupCode"].ToString();
                        dic["singleRow"] = r["singleRow"].ToString();
                        if (r["showType"].ToString() == "field")
                        {

                        }


                        var dr = table.Select("groupCode='" + r["groupCode"].ToString() + "'");
                        List<Dictionary<string, object>> clist = new List<Dictionary<string, object>>();
                        foreach (DataRow sr in dr)
                        {
                            var c_dic = new Dictionary<string, object>();
                            c_dic["fieldCode"] = sr["fieldCode"].ToString();
                            c_dic["fieldName"] = sr["fieldName"].ToString();
                            c_dic["fieldType"] = sr["fieldType"].ToString();
                            if (sr["fieldType"].ToString() == "fxlk" && !string.IsNullOrWhiteSpace(sr["dSoure"].ToString()))
                            {
                                var dtable = cmd.GetDataTable(sr["dSoure"].ToString());
                                string values = "";
                                foreach (DataRow qr in dtable.Rows)
                                {
                                    values += string.Format("{0},{1};", qr[0].ToString(), qr[1].ToString());
                                }
                                c_dic["dSoure"] = values.TrimEnd(';');
                            }
                            else
                            {
                                c_dic["dSoure"] = "";
                            }
                            clist.Add(c_dic);
                        }
                        dic["gfields"] = clist;
                        dlist.Add(dic);
                        reList.Add(r["groupCode"].ToString());
                    }
                }
                rsl.Data = dlist;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划工艺删除
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelPlanGongYi(string plCode, string gxCode, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbPlanTechnology pg = new DbPlanTechnology();
                pg.plCode = plCode;
                pg.gxCode = gxCode;
                pg.isdel = 1;
                pg.delMsg = string.Format("{0}({1})", userCode, System.DateTime.Now.ToString());
                oper = new OperateModel();
                oper.Data = pg;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "gxCode,plCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>

        /// 成品存货bom物料清单
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <param name="planNum">计划数量</param>
        /// <returns></returns>
        public ReturnResult GetProductBom(string pageIndex, string pageSize, string condition, ref string pageCount, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);

                DataTable dTable = new DataTable();
                dTable.Columns.Add("proCode");
                dTable.Columns.Add("proName");
                dTable.Columns.Add("unitCode");
                dTable.Columns.Add("unitName");
                dTable.Columns.Add("bzValue");
                dTable.Columns.Add("inNum");
                dTable.Columns.Add("useNum");
                dTable.Columns.Add("numType");
                dTable.Columns.Add("memo");

                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    rsl.Message = "存货信息不能为空"; return rsl;
                }
                sb.Append("bomDel=0 and isdel=0 and relationCode='" + json["proCode"].ToString() + "'");
                var list = cmd.PageList("V_BomSub_meterial", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);
                DataRow dr;
                if (!string.IsNullOrWhiteSpace(json["planNum"].ToString()) && double.Parse(json["planNum"].ToString()) > 0)
                {
                    foreach (var d in list)
                    {
                        dr = dTable.NewRow();
                        dr["proCode"] = d["materialCode"].ToString();
                        dr["proName"] = d["proName"].ToString();
                        dr["unitCode"] = d["unitCode"].ToString();
                        dr["unitName"] = d["unitName"].ToString();
                        dr["memo"] = d["memo"].ToString();
                        if (d["standardNum"] != null && !string.IsNullOrWhiteSpace(d["standardNum"].ToString()))
                        {
                            dr["bzValue"] = Math.Round(double.Parse(json["planNum"].ToString()) / double.Parse(d["standardNum"].ToString()) * double.Parse(d["number"].ToString()), 2);
                        }
                        else
                        {
                            dr["bzValue"] = "0";
                        }

                        #region 原辅料现存量查询
                        if (json["numType"].ToString() == "bar")
                        {
                            sb.Clear();
                            sb.Append("select isnull(sum(CONVERT(decimal(18,2),proWeight)),'0') pweight,isnull(sum(CONVERT(decimal(18,2),proMeter)),'0') pmeter ");
                            sb.Append("from bar_ProductBarCode_info ");
                            sb.Append("where proCode in (select proCode from fun_Inventory_Info where typeCode= '" + d["materialCode"].ToString() + "' and isdel=0 and status='Y')  and barStatus='need-out'");
                            var bTable = cmd.GetDataTable(sb.ToString());
                            #region 条码库存
                            dr["numType"] = "bar";
                            if (d["unitCode"].ToLower() == "kg")
                            {
                                dr["inNum"] = bTable.Rows[0]["pweight"].ToString();
                            }
                            else
                            {
                                dr["inNum"] = bTable.Rows[0]["pmeter"].ToString();
                            }
                            #endregion
                        }
                        else
                        {
                            #region 系统没有存货关联条码信息，查询U8现存量
                            dr["numType"] = "erp";
                            dr["inNum"] = ErpStockNumber(d["materialCode"].ToString(), baseCode);
                            #endregion
                        }
                        #endregion

                        #region 可用数量计算
                        sb.Clear();
                        sb.Append("select isnull(sum(CONVERT(decimal(18,2),number)),'0') from  pi_ProductsOccupation_list ");
                       // sb.Append("where isdel=0 and status='Y' and proCode='" + d["materialCode"].ToString() + "' and barCode!='' ");
                        sb.Append("where isdel=0 and status='Y' and proCode in (select proCode from fun_Inventory_Info where typeCode= '" + d["materialCode"].ToString() + "' and isdel=0 and status='Y') and barCode!='' ");
                        var zyTable = cmd.GetDataTable(sb.ToString());
                        dr["useNum"] = (double.Parse(dr["inNum"].ToString()) - double.Parse(zyTable.Rows[0][0].ToString()) ).ToString("0.0000");

                        #endregion
                        dTable.Rows.Add(dr);
                    }
                }

                rsl.Data = cmd.TableToDictionary(dTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 原料（无码）库存显示
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <param name="planNum">计划数量</param>
        /// <returns></returns>
        public ReturnResult GetBomStock_old(string pageIndex, string pageSize, string condition, ref string pageCount, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                DataTable dTable = new DataTable();
                dTable.Columns.Add("proCode");
                dTable.Columns.Add("proName");
                dTable.Columns.Add("spec");
                dTable.Columns.Add("unitCode");
                dTable.Columns.Add("unitName");
                dTable.Columns.Add("bzValue");
                dTable.Columns.Add("number");
                dTable.Columns.Add("zyNum");
                dTable.Columns.Add("kyNum");
                dTable.Columns.Add("numType");
                dTable.Columns.Add("wareHouse");
                dTable.Columns.Add("wareHouseName");

                sb.Append("");
         
                if (string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    rsl.Message = "存货信息不能为空"; return rsl;
                }
                sb.Append("bomDel=0 and isdel=0 and relationCode='" + json["proCode"].ToString() + "' ");
                if (!string.IsNullOrWhiteSpace(json["mProCode"].ToString()))
                {
                    sb.Append("and proCode like '%" + json["mProCode"].ToString() + "%'");
                }
                if (!string.IsNullOrWhiteSpace(json["proName"].ToString()))
                {
                    sb.Append("and proName like '%" + json["proName"].ToString() + "%'");
                }
                if (!string.IsNullOrWhiteSpace(json["spec"].ToString()))
                {
                    sb.Append("and spec like '%" + json["spec"].ToString() + "%'");
                }
                var list = cmd.PageList("V_Bom_MaterialList", pageIndex, pageSize, sb.ToString(), " specc,speccm ", ref pageCount);
                DataRow dr;
                if (!string.IsNullOrWhiteSpace(json["planNum"].ToString()) && double.Parse(json["planNum"].ToString()) > 0)
                {
                    foreach (var d in list)
                    {
                        #region 查询U8现存量
                        var sTable = this.ErpWhStockNumber(d["proCode"].ToString(), "", baseCode);
                        if (sTable.Rows.Count > 0)
                        {
                            foreach (DataRow rows in sTable.Rows)
                            {
                                dr = dTable.NewRow();
                                dr["proCode"] = d["proCode"].ToString();
                                //dr["proCode"] = d["materialCode"].ToString();
                                dr["proName"] = d["proName"].ToString();
                                dr["spec"] = d["spec"].ToString();
                                dr["unitCode"] = d["unitCode"].ToString();
                                dr["unitName"] = d["unitName"].ToString();
                                if (d["standardNum"] != null && !string.IsNullOrWhiteSpace(d["standardNum"].ToString()))
                                {
                                    dr["bzValue"] = Math.Round(double.Parse(json["planNum"].ToString()) / double.Parse(d["standardNum"].ToString()) * double.Parse(d["number"].ToString()), 2);
                                }
                                else
                                {
                                    dr["bzValue"] = "0";
                                }

                                dr["numType"] = "erp";
                                dr["number"] = rows["number"].ToString();
                                dr["wareHouse"] = rows["cWhCode"].ToString();
                                dr["wareHouseName"] = rows["cWhName"].ToString();

                                #region 可用数量计算
                                sb.Clear();
                                sb.Append("select isnull(sum(CONVERT(decimal(18,2),number)),'0') from  pi_ProductsOccupation_list ");
                                sb.Append("where isdel=0 and status='Y' and proCode='" + d["proCode"].ToString() + "' ");
                                sb.Append(" and wareHouse='" + rows["cWhCode"].ToString() + "' ");  //and barCode=''
                                var zyTable = cmd.GetDataTable(sb.ToString());
                                dr["zyNum"] = Math.Round(double.Parse(zyTable.Rows[0][0].ToString()), 2);
                                dr["kyNum"] = Math.Round(double.Parse(dr["number"].ToString()) - double.Parse(zyTable.Rows[0][0].ToString()), 2);

                                #endregion
                                dTable.Rows.Add(dr);
                            }
                        }
                        else
                        {
                            dr = dTable.NewRow();
                            dr["proCode"] = d["proCode"].ToString();
                            //dr["proCode"] = d["materialCode"].ToString();
                            dr["proName"] = d["proName"].ToString();
                            dr["spec"] = d["spec"].ToString();
                            dr["unitCode"] = d["unitCode"].ToString();
                            dr["unitName"] = d["unitName"].ToString();
                            if (d["standardNum"] != null && !string.IsNullOrWhiteSpace(d["standardNum"].ToString()))
                            {
                                dr["bzValue"] = Math.Round(double.Parse(json["planNum"].ToString()) / double.Parse(d["standardNum"].ToString()) * double.Parse(d["number"].ToString()), 2);
                            }
                            else
                            {
                                dr["bzValue"] = "0";
                            }
                            dr["numType"] = "erp";
                            dr["number"] = "0";
                            dr["wareHouse"] = "";
                            dr["wareHouseName"] = "";
                            dr["zyNum"] = "0";
                            dr["kyNum"] = "0";
                            dTable.Rows.Add(dr);
                        }


                        #endregion

                    }
                }

                rsl.Data = cmd.TableToDictionary(dTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult GetBomStock(string pageIndex, string pageSize, string condition, ref string pageCount, string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                DataTable dTable = new DataTable();
                dTable.Columns.Add("proCode");
                dTable.Columns.Add("proName");
                dTable.Columns.Add("spec");
                dTable.Columns.Add("unitCode");
                dTable.Columns.Add("unitName");
                dTable.Columns.Add("bzValue");
                dTable.Columns.Add("number");
                dTable.Columns.Add("zyNum");
                dTable.Columns.Add("kyNum");
                dTable.Columns.Add("numType");
                dTable.Columns.Add("wareHouse");
                dTable.Columns.Add("wareHouseName");
                if (json.Property("proCode")==null || string.IsNullOrWhiteSpace(json["proCode"].ToString()))
                {
                    rsl.Message = "关键参数成品存货编码缺失"; return rsl;
                }

                sb.Append("select materialCode,isnull(memo,'') spec,standardNum,number,unitCode,d.name unitName from bom_ProductionBom_sub s  ");
                sb.Append("inner join sys_dictionaries_info d on s.unitCode=d.code and d.types='prt' ");
                sb.Append(" where s.isdel=0 and bomCode in(select bomCode from bom_ProductionBom_main ");
                sb.Append(" where relationCode='" + json["proCode"] +"' and isdel=0) ");
                var bsTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in bsTable.Rows)
                {
                    sb.Clear();
                    sb.Append("select proCode,proName,spec from fun_Inventory_Info where typeCode='"+ r["materialCode"].ToString() +"'");
                    sb.Append(" and isdel=0 and status='Y' ");
                    if (json.Property("spec") != null && !string.IsNullOrWhiteSpace(json["spec"].ToString()))
                    {
                        sb.Append(" and spec like '%" + json["spec"].ToString().Trim() + "%'");
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(r["spec"].ToString()))
                        {
                            sb.Append(" and spec='" + r["spec"].ToString().Trim() + "'");
                        }
                    }
                    if (json.Property("mProCode") != null && !string.IsNullOrWhiteSpace(json["mProCode"].ToString()))
                    {
                        sb.Append(" and proCode like '%" + json["mProCode"].ToString().Trim() + "%'");
                    }
                    if (json.Property("proName") != null && !string.IsNullOrWhiteSpace(json["proName"].ToString()))
                    {
                        sb.Append(" and proName like '%" + json["proName"].ToString().Trim() + "%'");
                    }
                    var proTable = cmd.GetDataTable(sb.ToString());
                    foreach (DataRow pr in proTable.Rows)
                    {
                        string whereStr = "proCode='" + pr["proCode"].ToString() + "'";
                        if (!string.IsNullOrWhiteSpace(r["spec"].ToString()))
                        {
                            whereStr += " and spec='"+ r["spec"].ToString() +"'";
                        }
                        var q_dr = dTable.Select(whereStr);
                        if (q_dr.Length < 1)
                        {
                            string proCode= pr["proCode"].ToString();
                            string proName = pr["proName"].ToString();
                            string spec= pr["spec"].ToString();
                            string unitCode= r["unitCode"].ToString();
                            string unitName = r["unitName"].ToString();
                            double bzValue = 0;
                            bzValue = Math.Round(double.Parse(json["planNum"].ToString()) / double.Parse(r["standardNum"].ToString()) * double.Parse(r["number"].ToString()), 2);
                            #region
                            var sTable = this.ErpWhStockNumber(pr["proCode"].ToString(), "", baseCode);
                            if (sTable.Rows.Count < 1)
                            {
                                this.TempStock(proCode, proName, spec, unitCode, unitName, bzValue, "0", "", "", "0", "0", ref dTable);
                            }
                            else
                            {
                                foreach (DataRow rows in sTable.Rows)
                                {
                                    string wareCode = rows["cWhCode"].ToString();
                                    string wareName= rows["cWhName"].ToString();
                                    string stockNum= rows["number"].ToString();
                                    double zyNum =0, kyNum =0;
                                    sb.Clear();
                                    sb.Append("select isnull(sum(CONVERT(decimal(18,2),number)),'0') from  pi_ProductsOccupation_list ");
                                    sb.Append("where isdel=0 and status='Y' and proCode='" + proCode + "' ");
                                    sb.Append(" and wareHouse='" + wareCode + "' ");  //and barCode=''
                                    var zyTable = cmd.GetDataTable(sb.ToString());
                                    zyNum = Math.Round(double.Parse(zyTable.Rows[0][0].ToString()), 2);
                                    kyNum = Math.Round(double.Parse(stockNum) - double.Parse(zyTable.Rows[0][0].ToString()), 2);
                                    this.TempStock(proCode, proName, spec, unitCode, unitName, bzValue,stockNum, wareCode, wareName,zyNum.ToString(),kyNum.ToString(), ref dTable);
                                }
                            }
                          
                            #endregion
                        }
                    }
                }
                rsl.Data = cmd.TableToDictionary(dTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private void TempStock(string proCode,string proName,string spec,string unitCode,string unitName,double bzValue,string stockNum,string wareCode,string wareName ,string zyNum,string kyNum, ref DataTable dTable)
        {

            DataRow dRow = dTable.NewRow();
            dRow["proCode"] = proCode;
            dRow["proName"] = proName;
            dRow["spec"] = spec;
            dRow["unitCode"] = unitCode;
            dRow["unitName"] = unitName;
            dRow["bzValue"] = bzValue.ToString();
            dRow["numType"] = "erp";
            dRow["number"] = stockNum;
            dRow["wareHouse"] = wareCode;
            dRow["wareHouseName"] = wareName;
            dRow["zyNum"] = zyNum;
            dRow["kyNum"] = kyNum;
            dRow["numType"] = "erp";
            dTable.Rows.Add(dRow);
        }
        /// <summary>
        /// 计划原辅料占用
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult GetPlanZhanYong(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("plCode='" + condition + "' and isdel=0 and status='Y'");
                var list = cmd.PageList("V_PI_ProductsOccupation", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划待采购清单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult PurchaseList(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
               
                var json = JsonConvert.DeserializeObject<JObject>(condition);

                StringBuilder sb = new StringBuilder();
                sb.Append("plCode='" + json["plCode"].ToString() + "' ");
                var list = cmd.PageList("pi_PurchaseList", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult addPurchaseList(string plCode, string field, string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                operList = new List<OperateModel>();

                DBPurchaseList p = new DBPurchaseList();

                sb =new StringBuilder();
                sb.Append("select * from pi_PurchaseList where plCode='"+ plCode + "' and proCode='"+ json["proCode"].ToString() + "' ");
                var table = cmd.GetDataTable(sb.ToString());

                if(table.Rows.Count > 0)
                {
                    if (field == "memo")
                    {
                        #region 请购数量  修改
                        if (decimal.Parse(json["memo"].ToString()) < 0)
                        {
                            rsl.Message = "请购数量不能小于0";
                            return rsl;
                        }

                        p.plCode = plCode;
                        p.proCode = json["proCode"].ToString();

                        p.number = json["number"].ToString();//现存
                        p.bzValue = json["bzValue"].ToString();//需求
                        p.kyNum = json["kyNum"].ToString();//可用
                        p.memo = json["memo"].ToString();//采购

                        oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "plCode,proCode";
                        operList.Add(oper);
                        #endregion
                    }
                    else if (field == "useMeter")
                    {
                        #region  米数，修改
                        p.plCode = plCode;
                        p.proCode = json["proCode"].ToString();

                        p.number = json["number"].ToString();//现存
                        p.bzValue = json["bzValue"].ToString();//需求
                        p.kyNum = json["kyNum"].ToString();//可用

                        p.meter = json["useMeter"].ToString();//米数

                        oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "plCode,proCode";
                        operList.Add(oper);
                        #endregion
                    }
                }
                else
                {
                    if (field == "memo")
                    {
                        #region 请购数量  添加，必须得先填请购数量
                        if (decimal.Parse(json["memo"].ToString()) < 0)
                        {
                            rsl.Message = "请购数量不能小于0";
                            return rsl;
                        }

                        p.plCode = plCode;
                        p.proCode = json["proCode"].ToString();
                        p.proName = json["proName"].ToString();
                        p.spec = json["spec"].ToString();
                        p.unitName = json["unitName"].ToString();

                        p.number = json["number"].ToString();//现存
                        p.bzValue = json["bzValue"].ToString();//需求
                        p.kyNum = json["kyNum"].ToString();//可用
                        p.memo = json["memo"].ToString();//采购

                        oper = new OperateModel();
                        oper.Data = p;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }
                    else if (field == "useMeter")
                    {
                        #region  米数，提示先添加采购数量
                        rsl.Message = "请先添加采购数量";
                        return rsl;
                        #endregion
                    }
                }

               
                

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有保存数据";
                }
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }


        public ReturnResult DelPurchaseList(string id)
        {
            rsl = new ReturnResult();
            try
            {
                operList=new List<OperateModel>();
                DBPurchaseList p = new DBPurchaseList();
                p.id = Convert.ToInt32(id);

                oper = new OperateModel();
                oper.Data = p;
                oper.Types = OperateModel.OperateType.Delete;
                oper.Conditions = "id";
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {

                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// erp存货现存量
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        private string ErpStockNumber(string proCode, string baseCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select isnull(sum(iQuantity),'0') number from CurrentStock where cInvCode='" + proCode + "'");
            var table = outBase.getData(sb.ToString(), baseCode);
            return table.Rows[0][0].ToString();
        }

        /// <summary>
        /// erp存货现存量 按仓库汇总
        /// </summary>
        /// <param name="proCode"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public DataTable ErpWhStockNumber(string proCode,string wareHouse, string baseCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("select  isnull(sum(CONVERT(decimal(18,2),iQuantity)),'0') number ,cinvCode,s.cWhCode,w.cWhName ");
            sb.Append("from CurrentStock s inner join Warehouse w on s.cWhCode=w.cWhCode where cInvCode='" + proCode + "' ");
            if (!string.IsNullOrWhiteSpace(wareHouse))
            {
                sb.Append(" and s.cWhCode='" + wareHouse + "'");
            }
            sb.Append("group by cinvCode,s.cWhCode,w.cWhName ");
            var table = outBase.getData(sb.ToString(), baseCode);
            return table;
        }
        /// <summary>
        /// 现存量明细
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="condition"></param>
        /// <param name="pageCount"></param>
        /// <param name="baseCode"></param>
        /// <returns></returns>
        public ReturnResult StockDetail(string pageIndex, string pageSize, string condition, ref string pageCount, string baseCode)
        {
            try
            {
                rsl = new ReturnResult();
                var obj = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
               
                if (obj["numType"].ToString() == "bar")
                {
                    sb.Append(" barStatus='need-out' ");
                    if (obj.Property("proCode") != null && !string.IsNullOrWhiteSpace(obj["proCode"].ToString()))
                    {
                        sb.Append(" and proCode='" + obj["proCode"].ToString() + "'");
                    }
                    if (obj.Property("typeCode") != null && !string.IsNullOrWhiteSpace(obj["typeCode"].ToString()))
                    {
                        sb.Append(" and typeCode like '" + obj["typeCode"].ToString() + "%'");
                    }
                    if (obj.Property("spec") != null && !string.IsNullOrWhiteSpace(obj["spec"].ToString()))
                    {
                        sb.Append(" and spec like '%" + obj["spec"].ToString() + "%'");
                    } 
                    if (obj.Property("proName") != null && !string.IsNullOrWhiteSpace(obj["proName"].ToString()))
                    {
                        sb.Append(" and proName like '%" + obj["proName"].ToString() + "%'");
                    }

                    var list = cmd.PageList("V_Bar_ProductBarCode", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                    for (int i = 0; i < list.Count; i++)
                    {
                        sb.Clear();
                        sb.Append("select isnull(sum(CONVERT(decimal(18,2),number)),'0') num,");
                        sb.Append("STUFF((select plCode + ','  from pi_ProductsOccupation_list where isdel = 0 and status = 'Y' and barCode = s.barCode FOR XML path('')),1,0,'') as plCodes ");
                        sb.Append("from pi_ProductsOccupation_list s ");
                        sb.Append("where isdel=0 and status='Y' and barCode='" + list[i]["barCode"] + "'");
                        sb.Append("group by barCode ");

 
                        var table = cmd.GetDataTable(sb.ToString());
                        string zyNum = "0";
                        string zyPlCodes = "";
                        if (table.Rows.Count > 0)
                        {
                            zyNum = table.Rows[0][0].ToString();
                            zyPlCodes = table.Rows[0]["plCodes"].ToString().TrimEnd(',');
                        }
                        list[i]["zyNum"] = zyNum;
                        list[i]["zyPlCodes"] = zyPlCodes;
                        list[i]["kyNum"] = (double.Parse(list[i]["number"].ToString()) - double.Parse(zyNum)).ToString();//可用数量
                        list[i]["useNum"] = list[i]["kyNum"];
                    }

                    rsl.Data = list;
                    rsl.Result = true;
                }
                else
                {
                    #region erp库存
                    sb.Append("SELECT s.cInvCode proCode,s.cWhCode wareHouse,s.iQuantity number,s.fAvaQuantity useNum,");
                    sb.Append("p.cInvName proName,w.cWhName wareName FROM CurrentStock s");
                    sb.Append(" inner join inventory  p on p.cInvCode=s.cInvCode ");
                    sb.Append(" inner join Warehouse w on w.cWhCode=s.cWhCode  where s.cInvCode='" + obj["proCode"].ToString() + "'");
                    sb.Append(" ORDER BY s.AutoID desc ");
                    sb.Append("OFFSET " + int.Parse(pageSize) * int.Parse(pageIndex) + " ROWS FETCH NEXT " + pageSize + " ROWS ONLY");
                    var table = outBase.getData(sb.ToString(), baseCode);
                    rsl.Data = cmd.TableToDictionary(table);
                    rsl.Result = true;
                    #endregion
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 生产计划占用原辅料
        /// </summary>
        /// <param name="plCode">关联计划</param>
        /// <param name="cDatas">原辅料数据</param>
        /// <param name="numType">数据类型</param>
        /// <param name="userCode">人员</param>
        /// <returns></returns>
        public ReturnResult SavePlanMeterial(string plCode, string cDatas, string numType, string userCode, string gxCode, string gxName)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "计划编码不允许为空"; return rsl;
                }
                sb.Append("select * from pi_ProductsOccupation_list where plCode='" + plCode + "' and isdel=0 "); //and status='Y' 
                var zyTable = cmd.GetDataTable(sb.ToString());

                var jsons = JsonConvert.DeserializeObject<List<JObject>>(cDatas);
                DbProductsOccupation zyDb;
                foreach (var obj in jsons)
                {

                    bool isAdd = true;
                    string dataId = "";
                    zyDb = new DbProductsOccupation();
                    zyDb.plCode = plCode;
                    zyDb.status = "Y";
                    zyDb.isdel = 0;
                    zyDb.memo = "生产占用";
                    zyDb.createtime = getNow();
                    zyDb.createuser = userCode;
                    zyDb.number = obj["number"].ToString();
                    if (numType == "bar")
                    {
                        #region 条码占用
                        sb.Clear();
                        sb.Append("select * from bar_ProductBarCode_info where barCode='" + obj["keyCode"].ToString() + "'");
                        var bTable = cmd.GetDataTable(sb.ToString());
                        zyDb.proCode = bTable.Rows[0]["proCode"].ToString();
                        zyDb.barCode = obj["keyCode"].ToString();
                        zyDb.wareHouse = bTable.Rows[0]["wareHouse"].ToString();
                        if (string.IsNullOrWhiteSpace(obj["number"].ToString()) || obj["number"].ToString() == "0")
                        {
                            zyDb.number = bTable.Rows[0]["number"].ToString();
                        }
                        #endregion
                        var dr = zyTable.Select("barCode='" + obj["keyCode"].ToString() + "'");
                        if (dr.Length > 0)
                        {
                            dataId = dr[0]["id"].ToString();
                            isAdd = false;
                        }
                    }
                    else
                    {
                        double num = 0;
                        foreach (DataRow pr in zyTable.Rows)
                        {
                            if ((pr["barCode"] == null || string.IsNullOrWhiteSpace(pr["barCode"].ToString())) && pr["proCode"].ToString() == obj["proCode"].ToString())
                            {
                                num = double.Parse(pr["number"].ToString());
                                isAdd = false;
                                dataId = pr["id"].ToString();
                                break;
                            }
                        }
                        #region 无码原辅料占用
                        zyDb.number = (num + double.Parse(obj["useNum"].ToString())).ToString();
                        zyDb.proCode = obj["proCode"].ToString();
                        zyDb.barCode = "-";
                        zyDb.wareHouse = obj["wareHouse"].ToString();
                        #endregion
                    }

                    zyDb.gxCode = gxCode;
                    zyDb.gxName = gxName;

                    oper = new OperateModel();
                    oper.Data = zyDb;
                    if (isAdd)
                    {
                        oper.Types = OperateModel.OperateType.Add;
                    }
                    else
                    {
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        zyDb.id = int.Parse(dataId);
                    }

                    operList.Add(oper);


                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有数据"; return rsl;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除计划占用原辅料
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelPlanZhanYong(string dataId, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbProductsOccupation zyDb = new DbProductsOccupation();
                zyDb.id = int.Parse(dataId);
                zyDb.delMsg = string.Format("{0}({1})", userCode, getNow());
                zyDb.isdel = 1;
                oper = new OperateModel();
                oper.Data = zyDb;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }



        /// <summary>
        /// 保存原料采购申请，并生成U8 请购单
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="datas"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult SavePurchaseApply(string plCode, string createuser,string baseCode, string cdatas, string datas)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            operList = new List<OperateModel>();
            try
            {
                //var toUser = "";
                var json = JsonConvert.DeserializeObject<JObject>(cdatas);
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);

                #region 新，生成采购请购单

                U8Order u8 = new U8Order();

                rsl = u8.PurchaseRequisition(json, jsons,createuser,baseCode);

                if (rsl.Result)
                {
                    //清空待申请列表
                    operList = new List<OperateModel>();
                    DBPurchaseList pl = new DBPurchaseList();
                    pl.plCode = plCode;

                    oper = new OperateModel();
                    oper.Data = pl;
                    oper.Types = OperateModel.OperateType.Delete;
                    oper.Conditions = "plCode";
                    operList.Add(oper);
                    rsl = cmd.MoreUpdate(operList);
                }

                #endregion

                #region  旧，新增采购任务
                //#region 采购负责人
                //sb.Clear();
                //sb.Append("select parValue from sys_parameters_info where parCode = 'purchaseUser'");
                //var dt = cmd.GetDataTable(sb.ToString());
                //if (dt.Rows.Count < 1)
                //{
                //    toUser = "admin";
                //}
                //else
                //{
                //    toUser = dt.Rows[0]["parValue"].ToString();
                //}

                //#endregion

                //var list = new List<JObject>();
                //foreach (var obj in jsons)
                //{
                //    list.Add(new JObject
                //    {
                //        { "tip01" , "存货编码："+obj["proCode"].ToString() },
                //        { "tip02" , "存货名称："+obj["proName"].ToString() },
                //        { "tip03" , "数 量："+ obj["memo"].ToString()    }
                //    });
                //}

                //Dictionary<string, object> dic = new Dictionary<string, object>();
                //dic["businessType"] = "purchase";
                //dic["businessCode"] = plCode;
                //dic["toUser"] = toUser;
                //dic["datas"] = list;
                //dic["contents"] = "新增采购任务，请及时处理";
                //dic["memo"] = "采购申请";

                //AppBLL app = new AppBLL();
                //app.CreateMsgInfo(dic, createuser, ref operList);

                //if (operList.Count > 0)
                //{
                //    rsl = cmd.MoreUpdate(operList);
                //}
                //else
                //{
                //    rsl.Message = "没有数据";
                //    return rsl;
                //}
                #endregion
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划派工
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult PlanPaiGong(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);

                DbPlanInfo plan;
                foreach (var obj in jsons)
                {
                    plan = new DbPlanInfo();
                    plan.plCode = obj["plCode"].ToString();
                    plan.status = "ps-doing";

                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";
                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有数据";
                    return rsl;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划取消派工
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult PlanCancelPaiGong(string datas)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);

                DbPlanInfo plan;
                foreach (var obj in jsons)
                {
                    plan = new DbPlanInfo();
                    plan.plCode = obj["plCode"].ToString();
                    plan.status = "ps-pg-set";

                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";
                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有数据";
                    return rsl;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 计划工艺数据保存
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SavePlanTechnology(string datas, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                StringBuilder sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbPlanTechnology gy;
                if (!json.ContainsKey("plCode") || string.IsNullOrWhiteSpace(json["plCode"].ToString()))
                {
                    rsl.Message = "关联计划编码丢失"; return rsl;
                }
                if (!json.ContainsKey("gxCode") || string.IsNullOrWhiteSpace(json["gxCode"].ToString()))
                {
                    rsl.Message = "关联工序编码丢失"; return rsl;
                }
                sb.Append("select * from pi_ProductionPlan_gy where isdel=0 and plCode='" + json["plCode"].ToString() + "'");
                sb.Append(" and gxCode='" + json["gxCode"].ToString() + "'");
                var table = cmd.GetDataTable(sb.ToString());
                foreach (JProperty obj in json.Properties())
                {
                    if (obj.Value == null || string.IsNullOrWhiteSpace(obj.Value.ToString()))
                    {
                        continue;
                    }
                    if (obj.Name == "plCode" || obj.Name == "gxCode")
                    {
                        continue;
                    }
                    bool isAdd = true;
                    foreach (DataRow r in table.Rows)
                    {
                        if (r["fieldCode"].ToString() == obj.Name)
                        {
                            isAdd = false;
                            #region 表单值发生变化做修改操作
                            if (r["fieldValue"].ToString() != obj.Value.ToString() && userCode == r["createuser"].ToString())  
                            {
                                gy = new DbPlanTechnology();
                                gy.id = r["id"].ToString();
                                gy.fieldValue = obj.Value.ToString();
                                if (obj.Value.ToString() == "-")
                                {
                                    gy.isdel =1;
                                }
                                oper = new OperateModel();
                                oper.Data = gy;
                                oper.Types = OperateModel.OperateType.Edit;
                                oper.Conditions = "id";
                                operList.Add(oper);
                            }
                            #endregion
                            break;
                        }
                    }
                    #region 添加操作
                    if (isAdd)
                    {
                        gy = new DbPlanTechnology();
                        gy.plCode = json["plCode"].ToString();
                        gy.gxCode = json["gxCode"].ToString();
                        gy.id = Guid.NewGuid().ToString().Replace("-", "");
                        gy.fieldCode = obj.Name;
                        gy.fieldValue = obj.Value.ToString();
                        gy.createtime = getNow();
                        gy.createuser = userCode;
                        gy.isdel = 0;
                        oper = new OperateModel();
                        oper.Data = gy;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }
                    #endregion
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有要保存的数据";
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取计划工序工艺数据
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult GetPlanTechnologyForm(string plCode, string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select fieldCode,fieldValue from pi_ProductionPlan_gy where isdel=0 and  plCode='" + plCode + "'");
                sb.Append(" and gxCode='" + gxCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (table.Rows.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "没有数值"; return rsl;
                }
                foreach (DataRow dr in table.Rows)
                {
                    if (!dic.ContainsKey(dr["fieldCode"].ToString()))
                    {
                        dic[dr["fieldCode"].ToString()] = dr["fieldValue"].ToString();
                    }
                }
                rsl.Result = true;
                rsl.Data = dic;;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取计划工序工艺数据(打印用)
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult GetPlanTechnologyFormToPrint(string plCode, string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_gy gy ");
                sb.Append("inner join V_PI_ProductPlan_info info on info.plCode = gy.plCode ");
                sb.Append("where gy.plCode='" + plCode + "' and gxCode='" + gxCode + "'");

                var table = cmd.GetDataTable(sb.ToString());

                DataTable dataTable = new DataTable();

                #region 计划信息
                dataTable.Columns.Add("cuName");
                dataTable.Columns.Add("jfDate");
                dataTable.Columns.Add("finishDate");
                dataTable.Columns.Add("number");
                dataTable.Columns.Add("proName");
                dataTable.Columns.Add("spec");
                dataTable.Columns.Add("caizhi");
                dataTable.Columns.Add("orderMemo");

                var row = dataTable.NewRow();
                foreach (DataColumn dc in table.Columns)
                {
                    foreach (var c in dataTable.Columns)
                    {
                        if (c.ToString() == dc.ToString())
                        {
                            row[c.ToString()] = table.Rows[0][dc.ToString()].ToString();
                        }
                    }
                }

                dataTable.Rows.Add(row);
                #endregion

                #region 工艺信息
                foreach (DataRow dr in table.Rows)
                {
                    if (!dataTable.Columns.Contains(dr["fieldCode"].ToString()))
                        dataTable.Columns.Add(dr["fieldCode"].ToString());
                }

                foreach (DataRow dr in table.Rows)
                {
                    foreach (var c in dataTable.Columns)
                    {
                        if (c.ToString() == dr["fieldCode"].ToString())
                        {
                            row[c.ToString()] = dr["fieldValue"].ToString();
                        }
                    }
                }

                #endregion

            
                Dictionary<string, string> dic = new Dictionary<string, string>();
                if (dataTable.Rows.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "没有数值"; return rsl;
                }
                
                rsl.Result = true;
                rsl.Data =  cmd.TableToDictionary(dataTable);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 获取计划所用版辊信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <returns></returns>
        public ReturnResult GetBanGunByPlCode(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_fun_BanYangInfo where isdel=0 and byBarCode in(");
                sb.Append("select materialCode from  bom_ProductionBom_sub where isdel=0 and materialType='bangun'");
                sb.Append(" and bomCode in(select bomCode from pi_ProductionPlan_info where plCode='" + plCode + "'");
                sb.Append("))");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 生产计划（生产中）列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getPlanDoingList(JObject loginUser, string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }

                StringBuilder sb = new StringBuilder();
                string userCode = "", isAdmin = "", roleCode = "", gxs = "";
                #region 人员身份信息
                //获取登录人员权限信息
                userCode = loginUser["userCode"].ToString();
                isAdmin = loginUser["isAdmin"].ToString();
                roleCode = loginUser["powerRole"].ToString();

                #endregion

                #region 检索条件
                #region 除管理员和最高权限外   获取登录人负责工序
                if (isAdmin == "0" && !roleCode.Equals("R20221126113016"))
                {
                    sb.Append("select * from pi_GongXuUser_set where usCode='" + userCode + "'");
                    var guTable = cmd.GetDataTable(sb.ToString());
                    if (guTable.Rows.Count > 0)
                    {
                        foreach (DataRow dr in guTable.Rows)
                        {
                            gxs += "'" + dr["GongXu"].ToString() + "',";
                        }
                    }
                }
                #endregion 
                sb.Clear();
                sb.Append(" isdel=0 and status='ps-doing' ");
                if (!string.IsNullOrWhiteSpace(gxs))
                {
                    sb.Append("and gxCode in(" + gxs.TrimEnd(',') + ") ");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append(" convert(datetime,createtime, 20)" + " >='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {//结束时间
                                sb.Append(" convert(date,createtime, 20)" + "<= '" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                #endregion

                var tableName = "V_PI_ProductPlan_info";
                var list = cmd.PageList(tableName, pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);


                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult getPlanYongLiaoList(string pageIndex, string pageSize, ref string pageCount, string condition,string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(condition);
                sb = new StringBuilder();
                sb.Append("select l.*,i.proName,'' cjStock from pi_PlanMaterial_list l ");
                sb.Append("inner join fun_Inventory_Info i on i.proCode=l.proCode and i.isDel=0 ");
                sb.Append("where plCode='" + obj["plCode"].ToString() + "'");
                if (obj.Property("gxCode") != null && !string.IsNullOrWhiteSpace(obj["gxCode"].ToString()))
                {
                    sb.Append(" and gxCode='"+ obj["gxCode"].ToString() +"'");
                }
                var table = cmd.GetDataTable(sb.ToString());
                #region 多个车间库(Ning)
                var work_sql = "select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ";
                var wt = cmd.GetDataTable(work_sql);   //获取车间库编码
                //var workCode = "8";
                var workCode = "";
                if (wt.Rows.Count > 0)
                {
                    #region 多个仓库（Ning）
                    var ware = cmd.GetDataTable(work_sql).Rows[0]["parValue"].ToString();
                    var lists = ware.Split(',');
                    for (int i = 0; i < lists.Length; i++)
                    {
                        workCode += "'" + lists[i].ToString() + "',";
                    }
                    workCode = workCode.TrimEnd(',');
                    #endregion
                }
                #endregion

                foreach (DataRow dr in table.Rows)
                {
                    sb.Clear();
                    sb.Append("seleCt ISNULL(SUM(Convert(decimal(18, 2), iQuantity)),0) number from CurrentStock ");
                    sb.Append(" where cInvCode = '" + dr["proCode"].ToString() +"' and cBatch = '"+ dr["batch"].ToString()+"' and cWhCode in ("+ workCode + ") ");
                    var dt = outBase.getData(sb.ToString(), baseCode);
                    dr["cjStock"] = dt.Rows[0]["number"].ToString();
                }

                //添加一行空行
                var row = table.NewRow();
                table.Rows.Add(row);

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult getPlanWasteList(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var arrs = condition.Split(',');
                StringBuilder sb = new StringBuilder();
                sb.Append("select w.*,u.userName,c.cName gxName,c1.cName flTypeName,b.proCode,b.proName");
                sb.Append(",case when orderCode is null then '未入库' else  '已入库' end isIn from pi_PlanWaste_info w ");
                sb.Append("inner join bar_ProductBarCode_info b on w.reBarCode=b.barCode ");
                sb.Append("inner join sys_users_info u on u.userCode = w.createuser ");
                sb.Append("inner join fun_CommonData_Info c on c.cCode = w.gxCode and c.cType = 'GX' and c.status = 'Y' and c.isDel = '0' ");
                sb.Append("inner join fun_CommonData_Info c1 on c1.cCode=w.flType and c1.parentCode='flType' and c.status='Y' and c.isDel='0' ");
                sb.Append("where w.isdel=0 and plCode='" + arrs[0] + "' and w.gxCode='" + arrs[1] + "' ");
                var table = cmd.GetDataTable(sb.ToString());

                //添加一行空行
                //var row = table.NewRow();
                //table.Rows.Add(row);

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取存货某个批次最新单价
        /// </summary>
        /// <param name="prpCode">存货编码</param>
        /// <param name="batch">批次</param>
        /// <returns></returns>
        public string getProUprice(string proCode, string batch)
        {
            var price = "0";
            try
            {
                sb = new StringBuilder();

                sb.Append("seleCt * from V_U8_PurchasePrint where 1=1 and ");
                if (proCode.Contains("-"))
                {
                    //版辊带-，所以查版号
                    sb.Append(" cFree1= '" + proCode + "'");
                }
                else
                {
                    sb.Append(" cInvCode= '" + proCode + "'");
                }
                if (!string.IsNullOrEmpty(batch))
                {
                    sb.Append("and cBatch='" + batch + "' ");
                }
                else
                {
                    sb.Append("and cBatch is null ");
                }
                sb.Append("order by cCode desc");

                var table = cmd.GetDataTable(sb.ToString());

                if (table.Rows.Count > 0)
                {
                    price = Convert.ToDouble( table.Rows[0]["iUnitCost"].ToString()).ToString();
                }
            }
            catch (Exception ex)
            {
                price = "0";
            }
            return price;
        }

        /// <summary>
        /// 保存计划工序用料(空)
        /// </summary>
        /// <param name="datas">计划编码</param>
        /// <returns></returns>
        public ReturnResult savePlanMaterials(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(datas);
                var proCode = obj["proCodes"].ToString().Split(',');
                DBPlanYongLiao yl;
                operList = new List<OperateModel>();
                var mCode = getTimeString(); //操作码

                sb = new StringBuilder();
                sb.Append("select * from pi_PlanMaterial_list where plCode='" + obj["plCode"].ToString() + "'");
                sb.Append(" and gxCode='"+ obj["gxCode"].ToString() +"'");
                var table = cmd.GetDataTable(sb.ToString());

                foreach (var s in proCode)
                {
                    #region  不允许重复添加相同存货、批次的用料
                    var rows = table.Select("proCode='" + s.Split('-')[0].ToString() + "' and batch='" + s.Split('-')[1].ToString() + "'");
                    if (rows.Length > 0)
                    {

                        rsl.Message = "已添加批次为 " + s.Split('-')[1].ToString() + " 的 " + s.Split('-')[0].ToString() + " 用料信息";
                        return rsl;
                    }
                    #endregion

                    yl = new DBPlanYongLiao();
                    yl.plCode = obj["plCode"].ToString();
                    yl.gxCode= obj["gxCode"].ToString();
                    yl.proCode = s.Split('-')[0].ToString();
                    yl.batch = s.Split('-')[1].ToString();
                    yl.number = "0";
                    //yl.uPrice = "0";
                    #region  获取存货 批次的单价
                    var price = getProUprice(s.Split('-')[0].ToString(), s.Split('-')[1].ToString());
                    yl.uPrice = price;

                    yl.total = "0";
                    #endregion
                    yl.mType = "wmyl";//无码用料
                    yl.valueType = "1";//正数
                    yl.mCode = mCode;

                    oper = new OperateModel();
                    oper.Data = yl;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
                else
                {
                    rsl.Message = "没有要保存的数据";
                    rsl.Result = false;
                }

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 修改计划用料信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="proCodes">存货编码</param>
        /// <returns></returns>
        public ReturnResult updatePlanMaterials(string datas, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                StringBuilder sb = new StringBuilder();
                var mCode = getTimeString(); //操作码
                operList = new List<OperateModel>();
                DbPlanMaterialLists yls = new DbPlanMaterialLists();
                yls.createtime = getNow();
                yls.createuser = userCode;
                yls.isdel = 0;
                yls.number =json["fieldValue"].ToString();
                yls.dataId = json["dataId"].ToString();
                oper = new OperateModel();
                oper.Data = yls;
                oper.Types = OperateModel.OperateType.Add;
                oper.Conditions = "id";
                operList.Add(oper);

                sb.Append("select * from PI_PlanMaterial_list where id=" + json["dataId"].ToString());
                var mTable = cmd.GetDataTable(sb.ToString());
                double new_num=double.Parse(mTable.Rows[0]["number"].ToString())+double.Parse(json["fieldValue"].ToString());

                DBPlanYongLiao yl = new DBPlanYongLiao();
                yl.id = Convert.ToInt32(json["dataId"].ToString());
                yl.number = new_num.ToString();
                yl.total = (new_num * double.Parse(mTable.Rows[0]["uPrice"].ToString())).ToString();
                yl.mCode = mCode;
                oper = new OperateModel();
                oper.Data = yl;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);

                rsl = cmd.MoreUpdate(operList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 删除计划用料信息
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="proCodes">存货编码</param>
        /// <returns></returns>
        public ReturnResult DelPlanMaterials(string dataId,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                DBPlanYongLiao yl = new DBPlanYongLiao();

                yl.id = Convert.ToInt32(dataId);
                oper = new OperateModel();
                oper.Data = yl;
                oper.Types = OperateModel.OperateType.Delete;
                operList.Add(oper);

                DbPlanMaterialLists ppml = new DbPlanMaterialLists();
                ppml.dataId = dataId;
                ppml.isdel = 1;
                ppml.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper = new OperateModel();
                oper.Data = ppml;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "dataId";
                operList.Add(oper);

                rsl = cmd.Del(yl);


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 标记生产工序为完成
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult FinishPlanGx(string plCode, string gxCode, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                operList = new List<OperateModel>();

                #region 验证计划工序是否完成
                sb.Append("select id from pi_ProductionPlan_gx where plCode='" + plCode + "'");
                sb.Append(" and gxCode='" + gxCode + "' and isFinish=0");
                var xTable = cmd.GetDataTable(sb.ToString());
                if (xTable.Rows.Count < 1)
                {
                    rsl.Message = "计划工序已完成,无法重复完成"; return rsl;
                }
                #endregion

                #region 修改计划工序为完成状态
                DbPlanGx gx = new DbPlanGx();
                gx.plCode = plCode;
                gx.gxCode = gxCode;
                gx.isFinish = "1";
                gx.finishTime = getNow();
                gx.operateUser = userCode;
                oper = new OperateModel();
                oper.Data = gx;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode,gxCode";

                operList.Add(oper);

                #endregion

                #region 清空计划 工序占用的条码
                DbProductsOccupation oc = new DbProductsOccupation();
                oc.plCode = plCode;
                oc.gxCode = gxCode;
                oc.status = "N";
                oper = new OperateModel();
                oper.Data = oc;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "plCode,gxCode";

                operList.Add(oper);
                #endregion

                #region  如果计划其他工序也已经完成，则修改计划为完成状态
                sb.Clear();
                sb.Append("select distinct isFinish from pi_ProductionPlan_gx where isdel=0 and plCode='" + plCode + "' ");
                sb.Append(" and gxCode!='" + gxCode + "' order by isFinish");
                var table = cmd.GetDataTable(sb.ToString());

                //count<1 代表只有这一道工序，需要设置计划完成
                //count >1 并且 isfinish=1 出本工序外其它工序都完成了，设置计划完成
                if (table.Rows.Count < 1 || (table.Rows.Count > 0 && table.Rows[0]["isFinish"].ToString() == "1"))
                {
                    DbPlanInfo plan = new DbPlanInfo();
                    plan.plCode = plCode;
                    plan.status = "ps-finish";
                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";

                    operList.Add(oper);
                }

                #endregion

                #region 关联版辊
                /**完成工序为印刷，需要程序将关联版辊归还库房，并生成归还入库操作记录**/
                if (gxCode == "YS")
                {
                    sb.Clear();
                    sb.Append("select * from fun_BanYang_list where byBarCode in(select materialCode from bom_ProductionBom_sub ");
                    sb.Append("where bomCode in(");
                    sb.Append("select bomCode from pi_ProductionPlan_info where plCode='"+plCode+"'))");
                    var byTable=cmd.GetDataTable(sb.ToString());
                    if (byTable.Rows.Count > 0 && byTable.Rows[0]["status"].ToString()!="need-out")
                    {
                        #region 生成版辊归还记录
                        #region 构建参数
                        var work_sql = "select parValue from sys_parameters_info where parCode = 'work_warehouse_code' ";
                        var wt= cmd.GetDataTable(work_sql);   //获取车间库编码
                        var workCode = "8";
                        if(wt.Rows.Count > 0)
                        {
                            //workCode = wt.Rows[0]["parValue"].ToString();
                            #region 多个仓库（Ning）获得第一个
                            var ware = wt.Rows[0]["parValue"].ToString();
                            var lists = ware.Split(',');
                            
                            workCode = lists[0].ToString();
                            #endregion
                        }


                        string tempbarCodes = "";
                        List<string> barList = new List<string>();  //版辊编码
                        List<DbTempScanData> qList = new List<DbTempScanData>();
                        DbTempScanData temp ;
                        foreach (DataRow dr in byTable.Rows)
                        {
                            barList.Add(dr["byBarCode"].ToString());
                            temp = new DbTempScanData();
                            temp.happenDate = getNowDate();
                            temp.wareHouse = workCode;//车间库（旭日：8 ，本地测试：8）
                            temp.isBlue = "1";
                            temp.createuser = userCode;
                            temp.typeCode = "";//U8出入库类别
                            temp.operateDept = "";  //操作部门
                            temp.outOrderCode = ""; //关联的U8单据号
                            temp.barCode = dr["byBarCode"].ToString();
                            temp.memo = "印刷工序完成，手动归还版辊信息";
                            temp.operateType = "01";
                            qList.Add(temp);
                        }

                        var cCode = getTimeString();//单据的临时编码
                        Dictionary<string, object> tempdic = new Dictionary<string, object>();
                        tempdic.Add("mCode", cCode);//临时编码
                        tempdic.Add("inOutType", "pibg");  //版辊入库
                        tempdic.Add("type", "pibg");
                        tempdic.Add("outOrderCode", "");//U8单号
                        tempdic.Add("baseCode", "");
                        tempdic.Add("barList", barList);


                        #endregion

                        #region 添加主表和子表出入库记录    修改条码状态，添加计划用料信息
                        ServiceBLL service = new ServiceBLL();
                        service.insertMain(tempdic, qList, ref operList, "PC");
                        rsl = service.insertList(tempdic, qList, ref operList, ref tempbarCodes, null);
                        if (!rsl.Result)
                        {
                            return rsl;
                        }
                        #endregion

                        #endregion
                    }
                }
                #endregion

                rsl = cmd.MoreUpdate(operList);


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 标记生产计划为完成
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码</param>
        /// <returns></returns>
        public ReturnResult FinishPlan(string datas, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                operList = new List<OperateModel>();
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);

                foreach (var obj in jsons)
                {
                    #region 验证生产计划是否完成
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_info where plCode='" + obj["plCode"].ToString() + "' ");
                    sb.Append(" and status='ps-finish'");
                    var table = cmd.GetDataTable(sb.ToString());
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = "生产计划" + obj["plCode"].ToString() + "已完成,无法重复完成";
                        continue;
                    }
                    #endregion

                    #region  修改计划为完成状态
                    DbPlanInfo plan = new DbPlanInfo();
                    plan.plCode = obj["plCode"].ToString();
                    plan.status = "ps-finish";
                    oper = new OperateModel();
                    oper.Data = plan;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";

                    operList.Add(oper);
                    #endregion

                    #region 修改计划工序为完成状态
                    DbPlanGx gx = new DbPlanGx();
                    gx.plCode = obj["plCode"].ToString();
                    gx.isFinish = "1";
                    gx.finishTime = getNow();
                    gx.operateUser = userCode;
                    oper = new OperateModel();
                    oper.Data = gx;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "plCode";

                    operList.Add(oper);

                    #endregion
                }



                rsl = cmd.MoreUpdate(operList);


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }


        /// <summary>
        /// 添加计划废料信息
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddPlanWaste(string datas, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                sb = new StringBuilder();
                var json = JsonConvert.DeserializeObject<JObject>(datas);

                sb.Append("select * from pi_ProductionPlan_gx where plCode='" + json["plCode"].ToString() + "' and isdel=0");
                sb.Append(" and gxCode='" + json["gxCode"].ToString() + "' and isFinish=0");
                var dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count < 1)
                {
                    rsl.Message = "工序已完成或无法查找到关联工序";
                    return rsl;
                }

                #region 获取条码存货批次的单价信息
                sb.Clear();
                sb.Append("select proCode,cu_batch from bar_ProductBarCode_info where barCode='"+ json["barCode"].ToString() + "' ");
                dt = cmd.GetDataTable(sb.ToString());
                if (dt.Rows.Count < 1)
                {
                    rsl.Message = "未找到关联条码信息";
                    return rsl;
                }
                var uPrice = getProUprice(dt.Rows[0]["proCode"].ToString(), dt.Rows[0]["cu_batch"].ToString());
                #endregion

                #region 添加废料信息
                DBPlanWaste waste = new DBPlanWaste();
                waste.plCode = json["plCode"].ToString();
                waste.gxCode = json["gxCode"].ToString();
                waste.reBarCode = json["barCode"].ToString();
                waste.flType = json["flType"].ToString();
                waste.number = json["number"].ToString();
                waste.createuser = userCode;
                waste.createtime = getNow();
                waste.isdel = 0;
                waste.uPrice = uPrice;

                oper= new OperateModel();
                oper.Data = waste;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);

                #endregion

                #region 条码录入废料，如果勾选使用完成，则条码状态改为使用完成 
                if (json["useFinish"].ToString()=="1")
                {
                    DbProductBarCode bar = new DbProductBarCode();
                    bar.barStatus = "used-finish";
                    bar.barCode= json["barCode"].ToString();

                    oper = new OperateModel();
                    oper.Data = bar;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "barCode";

                    operList.Add(oper);
                }
                #endregion

                //rsl = cmd.Add(waste);
                rsl = cmd.MoreUpdate(operList);


            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除计划废料信息
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult DelPlanWaste(string dataId, string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DBPlanWaste waste = new DBPlanWaste();
                waste.id = Convert.ToInt32(dataId);
                waste.isdel = 1;
                waste.delMsg = getNow() + " " + userCode;

                oper = new OperateModel();
                oper.Data = waste;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";

                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 计划分切单
        /// </summary>
        /// <param name="plCode">计划编码</param>
        /// <param name="gxCode">工序编码（可能存在多道分切工序）</param>
        /// <returns></returns>
        public ReturnResult FenQieList(string plCode,string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(plCode))
                {
                    rsl.Message = "没有关联计划编码"; return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from pi_ProductionPlan_gy where plCode='" + plCode + "'");
                sb.Append(" and gxCode='"+ gxCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                List<Dictionary<string, object>> dList = new List<Dictionary<string, object>>();
                for (int i = 0; i < 5; i++)
                {
                    string proCode = "", proName = "", spec = "", num = "", fqValue = "", fqSpec = "";
                 
                    #region 查询工艺表单值
                    proCode = getFqString(table, "fqczCode" + (i + 1)); 
                    if (string.IsNullOrWhiteSpace(proCode))
                    {
                        continue;
                    }
                    fqSpec = getFqString(table, "fqSepc" + (i + 1));//分切规格
                    proName = getFqString(table, "fqczName" + (i + 1));
                    spec = getFqString(table, "clSpec" + (i + 1));
                    num = getFqString(table, "clNum" + (i + 1));//原辅料卷数
                    fqValue = getFqString(table, "fqNum" + (i + 1)); //分切米数(重量)
                    var dic = new Dictionary<string, object>();
                    dic["proCode"] = proCode;
                    dic["proName"] = proName;
                    dic["spec"] = spec;
                    dic["number"] = num;
                    dic["fqSpecs"] = fqSpec;
                    var fqArr = fqSpec.Split('+');
                    var clist = new List<Dictionary<string, string>>();
                    foreach (string fq in fqArr)
                    {
                        if (!string.IsNullOrWhiteSpace(fq))
                        {
                           var c_dic = new Dictionary<string, string>();

                          //  c_dic["num"] = "1";
                            c_dic["fqValue"] = fqValue;
                            c_dic["fqSpec"] = fq;
                            clist.Add(c_dic);
                        }
                    }
                    dic["fqList"] = clist;
                    dList.Add(dic);
                    #endregion
                    
                }
                rsl.Data = dList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        private string getFqString(DataTable table,string fieldCode)
        {
           var dr = table.Select("fieldCode='" + fieldCode + "'");
            if (dr.Length > 0)
            {
                return dr[0]["fieldValue"].ToString();
            }
            return "";
        }
        /// <summary>
        /// 将计划废料信息 生成其他入库单
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult SavePlanWasteAsRd08(string datas, string userCode, string baseCode, string dept)
        {
            rsl = new ReturnResult();
            try
            {
                List<string> sqlList = new List<string>();
                sb = new StringBuilder();
                if (string.IsNullOrEmpty(dept))
                {
                    rsl.Message = "未获取到当前用户部门信息";
                    return rsl;
                }
                var json = JsonConvert.DeserializeObject<JObject>(datas);


                sb.Clear();
                sb.Append("select parValue,parCode from sys_parameters_info where parCode in('flInWh','flCode') ");
                var dt = cmd.GetDataTable(sb.ToString());


                #region  废料信息
                var flCode = "";
                var flName = "";
                var rows = dt.Select("parCode = 'flCode' ");
                if (rows.Length > 0)
                {
                    var values = rows[0]["parValue"].ToString().Split(',');
                    flCode = values[0];
                    flName = values[1];
                }
                else
                {
                    rsl.Message = "无废料编码信息";
                    return rsl;
                }

                sb.Clear();
                //sb.Append("select w.reBarCode,w.number ,b.proCode,b.proName,b.cu_batch ");
                sb.Append("select sum(CONVERT(decimal(18,2),number)) number,'" + flCode + "' proCode,");
                sb.Append("'" + flName + "' proName,'' cu_batch,orderCode from pi_PlanWaste_info  where isdel=0 ");
                sb.Append(" and plCode='" + json["plCode"].ToString() + "' and gxCode='" + json["gxCode"].ToString() + "'");
                sb.Append(" and (orderCode is null or orderCode='')");
                sb.Append("group by orderCode order by orderCode desc  ");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "未获取到废料信息";
                    return rsl;
                }

                if (table.Rows.Count > 0 && !string.IsNullOrEmpty(table.Rows[0]["orderCode"].ToString()))
                {
                    rsl.Message = "当前工序废料已入库";
                    return rsl;
                }
                #endregion

                #region 条码录入废料，系统默认条码使用完成 【已注释，改成录入条码时手动选择是否使用完成并修改状态】
                //sb.Clear();
                //sb.Append("update bar_ProductBarCode_info set barStatus='used-finish' where barCode in ( ");
                //sb.Append("select reBarCode from pi_PlanWaste_info where isdel=0");
                //sb.Append(" and plCode='" + json["plCode"].ToString() + "' and gxCode='" + json["gxCode"].ToString() + "'");
                //sb.Append(" )");
                //sqlList.Add(sb.ToString());
                #endregion

                #region 其他入库 入的 仓库 和 入库类别 信息
                var wareHouse = "003";
                var rdcode = "31";
                rows = dt.Select("parCode = 'flInWh' ");
                if (rows.Length > 0)
                {
                    var values = rows[0]["parValue"].ToString().Split(',');
                    wareHouse = values[0];
                    rdcode = values[1];
                }
                #endregion

                string orderCode = "";
                if (AppSettingHelper.ReadAppSettings("ConntectERP") == "1")
                {//开启ERP系统对接，废料生成其他入库单
                    U8Order order = new U8Order();
                    rsl = order.FlOtherIn(table, userCode, baseCode, wareHouse, dept, rdcode);
                    if (rsl.Result)
                    {
                        orderCode = rsl.Data.ToString();
                    }
                    else
                    {
                        return rsl;
                    }
                    #region 记录ERP入库单编码
                    sb = new StringBuilder();
                    sb.Append("update pi_PlanWaste_info set orderCode='" + orderCode + "' ");
                    sb.Append("where isdel='0' and plCode='" + json["plCode"].ToString() + "' and gxCode='" + json["gxCode"].ToString() + "'");
                    sqlList.Add(sb.ToString());
                    #endregion
                }
                rsl = cmd.MoreUpdate(sqlList);

                if (rsl.Result)
                {
                    rsl.Message = "已成功入库";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;

        }
        /// <summary>
        /// 计划工序完成情况统计
        /// </summary>
        /// <param name="plCode"></param>
        /// <returns></returns>
        public ReturnResult PlanProcessProduction(string plCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select g.gxCode,g.isFinish,g.startTime,g.finishTime,c.cName gxName,'' num,'' total,gxOrder from pi_ProductionPlan_gx g");
                sb.Append(" inner join fun_CommonData_info c on c.cCode=g.gxCode and c.cType='gx' where g.plCode='" + plCode + "' and g.isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in table.Rows)
                {
                    sb.Clear();
                    sb.Append("select isnull(number,'0') number from bar_ProductBarCode_info where planCode='" + plCode + "'");
                    sb.Append(" and gxCode='" + r["gxCode"].ToString() + "' and barStatus !='bar-drop'");
                    var barTable = cmd.GetDataTable(sb.ToString());
                    r.BeginEdit();
                    r["num"] = barTable.Rows.Count;
                    double total = 0;
                    foreach (DataRow br in barTable.Rows)
                    {

                        total += double.Parse(br["number"].ToString());
                    }
                    r["total"] = total;
                    r.EndEdit();
                }
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;

            }
            return rsl;
        }
        /// <summary>
        /// 根据计划编码获取计划废料
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="plCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult GetPlanWaste(string pageIndex, string pageSize, string plCode, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("isdel=0 and plCode='" + plCode + "'");
                var list = cmd.PageList("V_PI_PlanWaste", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 运费单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="plCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult GetFerightList(string pageIndex, string pageSize, string condition, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "sDate")
                            {
                                sb.Append("convert(hDate,createtime)>='" + obj.Value.ToString() + "' ");
                            }
                            else if (obj.Name == "eDate")
                            {
                                sb.Append("convert(hDate,createtime)<='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                        }
                    }
                }
                var list = cmd.PageList("V_PI_FreightMain", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 运费明细
        /// </summary>
        /// <param name="ftCode"></param>
        /// <returns></returns>
        public ReturnResult FreightDetail(string ftCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_PI_FreightSub where ftCode='" + ftCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除运费单
        /// </summary>
        /// <param name="ftCode"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelFreightInfo(string ftCode, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                DbPlanFreightMain fMain = new DbPlanFreightMain();
                fMain.ftCode = ftCode;
                fMain.isdel = 1;
                fMain.delMsg = string.Format("{0}({1})", userCode, getNow());
                oper = new OperateModel();
                oper.Data = fMain;
                oper.Conditions = "ftCode";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);

                DbPlanFreightSub fSub = new DbPlanFreightSub();
                fSub.ftCode = ftCode;
                fSub.isdel = 1;
                oper = new OperateModel();
                oper.Data = fSub;
                oper.Conditions = "ftCode";
                oper.Types = OperateModel.OperateType.Edit;
                operList.Add(oper);

                string sql = "select distinct mCode from pi_Freight_sub where ftCode='" + ftCode + "' and isdel=0";
                var qTable = cmd.GetDataTable(sql);
                DbBarRecordsMain rdMain;
                foreach (DataRow r in qTable.Rows)
                {
                    rdMain = new DbBarRecordsMain();
                    rdMain.isCount = 0;
                    rdMain.mCode = r["mCode"].ToString();
                    oper = new OperateModel();
                    oper.Data = rdMain;
                    oper.Conditions = "mCode";
                    oper.Types = OperateModel.OperateType.Edit;
                    operList.Add(oper);
                }
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>

        /// 获取任务中心任务
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="plCode"></param>
        /// <param name="pageCount"></param>
        /// <returns></returns>
        public ReturnResult getTaskCenter(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);

                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("select *,case when isFinish=1 then '已处理' else '待处理' end finishType from V_TaskCenter ");
                var tableName= sb.ToString();

                sb.Clear();
                sb.Append(" businessType='purchase' and sysTypes='pcTask' ");
                if (json.Property("isFinish") != null && !string.IsNullOrWhiteSpace(json["isFinish"].ToString()))
                {
                    sb.Append(" and isFinish=" + json["isFinish"].ToString() + " ");
                }
                if (json.Property("relationOrder") != null && !string.IsNullOrWhiteSpace(json["relationOrder"].ToString()))
                {
                    sb.Append(" and relationOrder like'%" + json["relationOrder"].ToString() + "%'");
                }
                var sqlWhere = sb.ToString();
                var orderStr = "createtime desc";

                var pageNumber = "0";
                //var list = cmd.PageList("V_PI_PlanWaste", pageIndex, pageSize, sb.ToString(), "createtime desc", ref pageCount);
                var list = cmd.TableToDictionary(cmd.PageTableList(tableName, "1", pageSize, sqlWhere, orderStr, ref pageCount, ref pageNumber));

                var temList = new List<Dictionary<string, string>>();
                foreach ( var item in list )
                {
                    if (!string.IsNullOrWhiteSpace(item["details"].ToString()))
                    {
                        var text = "";
                        temList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(item["details"].ToString());
                        foreach (var s in temList)
                        {
                            text = text + s["tip02"] + "&nbsp&nbsp&nbsp" + s["tip03"]+" </br>";
                        }

                        item.Add("text", text.TrimEnd(','));
                    }
                    
                }

                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }

        /// <summary>
        /// 任务中心任务处理
        /// </summary>
        public ReturnResult taskConfirm(string ids,string userCode)
        {
            rsl=new ReturnResult();
            ServiceBLL serviceBLL = new ServiceBLL();
            try
            {
                var dic = new Dictionary<string, string>();
                dic["id"] = ids;
                dic["createuser"] = userCode;

                var json = JsonConvert.SerializeObject(dic);

                //var a = JsonConvert.DeserializeObject<JObject>(json);

                rsl = serviceBLL.taskConfirm(json);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }

            return rsl;
        }


        /// <summary>
        /// 获取工艺原辅料数据
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public ReturnResult GongYiMaterial(string plCode, string gxCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.proCode,b.proName,b.spec,zy.number zyNumber from V_BarCode_Info b ");
                sb.Append("inner join pi_ProductsOccupation_list zy on zy.barCode=b.barCode and plCode='" + plCode + "'");
                sb.Append(" and zy.gxCode='" + gxCode + "' and isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());
                List<string> reList = new List<string>();
                string proNames = "", spec = "", jianshu = "0", zyNumber = "0";
                foreach (DataRow r in table.Rows)
                {
                    if (!reList.Contains(r["proCode"].ToString()))
                    {
                        proNames += r["proName"].ToString() + ",";
                        spec += r["spec"].ToString() + ",";
                        var dr = table.Select("proCode='" + r["proCode"].ToString() + "'");
                        jianshu = dr.Length.ToString() + ",";
                        zyNumber = r["zyNumber"].ToString() + ",";
                        reList.Add(r["proCode"].ToString());
                    }
                }
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic["proNames"] = proNames.TrimEnd(',');
                dic["spec"] = spec.TrimEnd(',');
                dic["jianshu"] = jianshu.TrimEnd(',');
                dic["zyNumber"] = zyNumber.TrimEnd(',');
                rsl.Result = true;
                rsl.Data = dic;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 获取工艺原辅料数据
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public ReturnResult FHGongYiMaterial(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var obj = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.cu_material,b.cu_batch,b.proCode,b.proName,b.spec,zy.number zyNumber,vendorName,zy.slNum,zy.id ");
                sb.Append("from pi_ProductsOccupation_list zy inner join V_BarCode_Info b on zy.barCode=b.barCode ");
                sb.Append(" and zy.plCode='" + obj["plCode"]  + "' and zy.gxCode like'%" + obj["gxCode"] + "%' and zy.isdel=0 ");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult SaveShengLiao(string dataId, string value)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(dataId) || string.IsNullOrWhiteSpace(value))
                {
                    rsl.Message = "无需保存的数据";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("update pi_ProductsOccupation_list set slNum='"+ value +"' ");
                sb.Append("where id="+dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 销售出库存货列表(添加运费用)
        /// </summary>
        /// <param name="mCodes"></param>
        /// <returns></returns>
        public ReturnResult GetSaleOutProductList(string mCodes)
        {
            rsl = new ReturnResult();
            try
            {
                string codes = "";
                var arr = mCodes.Split(',');
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                        codes += "'" + code + "',";
                    }
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.proCode,b.proName,count(l.barCode) barCount from bar_BarEntryRecords_list l");
                sb.Append(" inner join  V_BarCode_Info b on l.barCode=b.barCode  where l.mCode in(" + codes.TrimEnd(',') + ")");
                sb.Append("  group by b.proCode,b.proName");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 添加销售出库运费
        /// </summary>
        /// <param name="mCodes"></param>
        /// <param name="datas"></param>
        /// <returns></returns>
        public ReturnResult AddPlanFreight(string mCodes, string datas, string memo, string userCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                string codes = "";
                var arr = mCodes.Split(',');
                DbBarRecordsMain dbMain;
                foreach (string code in arr)
                {
                    if (!string.IsNullOrWhiteSpace(code))
                    {
                        codes += "'" + code + "',";
                        dbMain = new DbBarRecordsMain();
                        dbMain.mCode = code;
                        dbMain.isCount = 1;
                        oper = new OperateModel();
                        oper.Data = dbMain;
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "mCode";
                        operList.Add(oper);
                    }

                }
                string ftCode = "OS" + getTimeString();
                StringBuilder sb = new StringBuilder();
                sb.Append("select b.proCode,b.proName,l.barCode,l.id,l.mCode from bar_BarEntryRecords_list l");
                sb.Append(" inner join  bar_ProductBarCode_info b on l.barCode=b.barCode  where l.mCode in(" + codes.TrimEnd(',') + ")");
                var rdTable = cmd.GetDataTable(sb.ToString());
                var jsons = JsonConvert.DeserializeObject<List<JObject>>(datas);
                DbPlanFreightSub fsub;
                double total = 0;
                foreach (var obj in jsons)
                {
                    double songhuo = 0, yunfei = 0;
                    if (obj.ContainsKey("songhuofei"))
                    {
                        if (!string.IsNullOrWhiteSpace(obj["songhuofei"].ToString()))
                        {
                            songhuo = double.Parse(obj["songhuofei"].ToString());
                        }
                    }

                    if (obj.ContainsKey("wuliufei"))
                    {
                        if (!string.IsNullOrWhiteSpace(obj["wuliufei"].ToString()))
                        {
                            yunfei = double.Parse(obj["wuliufei"].ToString());
                        }
                    }
                        
               
                    total += songhuo + yunfei;
                    var dr = rdTable.Select("proCode='" + obj["proCode"].ToString() + "'");
                    foreach (DataRow r in dr)
                    {
                        fsub = new DbPlanFreightSub();
                        fsub.mCode = r["mCode"].ToString();
                        fsub.barCode = r["barCode"].ToString();
                        fsub.yunfei = Math.Round(yunfei / int.Parse(obj["barCount"].ToString()), 2).ToString();
                        fsub.songhuo = Math.Round(songhuo / int.Parse(obj["barCount"].ToString()), 2).ToString();
                        fsub.isdel = 0;
                        fsub.ftCode = ftCode;
                        oper = new OperateModel();
                        oper.Data = fsub;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                    }
                }
                DbPlanFreightMain fMain = new DbPlanFreightMain();
                fMain.createuser = userCode;
                fMain.createtime = getNow();
                fMain.hDate = getNowDate();
                fMain.ftCode = ftCode;
                fMain.total = total.ToString();
                fMain.memo = memo;
                fMain.isdel = 0;
                oper = new OperateModel();
                oper.Data = fMain;
                oper.Types = OperateModel.OperateType.Add;
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        public ReturnResult GetPrintGYData(string queStr)
        { 
             rsl=new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where parCode='pGyData'");
                var pTable = cmd.GetDataTable(sb.ToString());
                if (pTable.Rows.Count > 0)
                {
                    var jsons = JsonConvert.DeserializeObject<List<JObject>>(pTable.Rows[0]["parValue"].ToString());
                    var obj = JsonConvert.DeserializeObject<JObject>(queStr);
                    sb.Clear();
                    sb.Append("select * from pi_ProductionPlan_gy where plCode='"+ obj["plCode"].ToString() +"'");
                    sb.Append(" and gxCode='"+ obj["gxCode"].ToString() +"' and isdel=0");
                    var gyTable = cmd.GetDataTable(sb.ToString());
                    var dic = new Dictionary<string, string>();
                    foreach (var gyJson in jsons)
                    {
                        if (gyJson["gxCode"].ToString().Trim() == obj["gxCode"].ToString().Trim())
                        {
                            var arr = gyJson["fields"].ToString().Split(',');
                            foreach (var f in arr)
                            {
                                if (!string.IsNullOrWhiteSpace(f))
                                {
                                    var dr = gyTable.Select("fieldCode='" + f + "'");
                                    if (dr.Length > 0)
                                    {
                                        dic[f] = dr[0]["fieldValue"].ToString();
                                    }
                                    else
                                    {
                                        dic[f] = "";
                                    }
                                }
                            }
                            break;
                        }
                    }
                    rsl.Data = dic;
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        public ReturnResult GetPPMList(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(condition);
                StringBuilder sb = new StringBuilder();
                sb.Append("select l.*,u.userName from PI_PlanMaterial_lists l  inner join sys_users_info u on l.createuser=u.userCode ");
                sb.Append(" where l.isdel=0 and dataId='" + json["dataId"] +"'");
                var table=cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 用料记录删除
        /// </summary>
        /// <param name="dataId"></param>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelPPMList(string dataId,string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                operList = new List<OperateModel>();
                DbPlanMaterialLists ppml = new DbPlanMaterialLists();
                ppml.id =int.Parse(dataId);
                ppml.isdel = 1;
                ppml.delMsg = string.Format("{0}({1})",userCode,getNow());
                oper = new OperateModel();
                oper.Data = ppml;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);
       
                sb.Append("select * from PI_PlanMaterial_lists where id="+dataId);
                var sTable=cmd.GetDataTable(sb.ToString());
                var mId = sTable.Rows[0]["dataId"].ToString();
                var num= sTable.Rows[0]["number"].ToString();

                sb.Clear();
                sb.Append("select * from PI_PlanMaterial_list where id=" + mId);
                var mTable = cmd.GetDataTable(sb.ToString());
                string mNum = mTable.Rows[0]["number"].ToString();
                string uPrice= mTable.Rows[0]["uPrice"].ToString();

                DBPlanYongLiao yl = new DBPlanYongLiao();
                yl.id=int.Parse(mId);
                yl.number = (double.Parse(mNum) - double.Parse(num)).ToString();
                yl.total = (double.Parse(uPrice)* (double.Parse(mNum) - double.Parse(num))).ToString();
                oper = new OperateModel();
                oper.Data = yl;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);
                rsl = cmd.MoreUpdate(operList);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 导出工艺信息
        /// </summary>
        /// <param name="plCode"></param>
        /// <param name="gxCode"></param>
        /// <returns></returns>
        public MemoryStream gyPrintToExcel(string plCode, string gxCode, ref string newFileName)
        {
            MemoryStream ms = null;
            sb = new StringBuilder();
            try
            {
                sb.Append("select gy.* ,p.cuName,p.number,p.finishDate,p.proName,p.spec,p.caizhi,p.memo,p.createtime hDate ");
                sb.Append("from pi_ProductionPlan_gy gy ");
                sb.Append("inner join V_PI_ProductPlan_info p on p.plCode = gy.plCode and p.isdel=0 ");
                sb.Append("where gy.plCode = '" + plCode + "' and gy.gxCode = '" + gxCode + "' and gy.isdel=0  ");
                var table = cmd.GetDataTable(sb.ToString());

                sb.Clear();
                sb.Append("select top 1 isFinish,isnull(finishTime,'') finishTime from pi_ProductionPlan_gx");
                sb.Append("  where plCode = '" + plCode + "'and gxCode = '" + gxCode + "' and isdel=0 order by id desc ");
                var gxTable = cmd.GetDataTable(sb.ToString());

                sb.Clear();
                sb.Append("select b.cu_material,b.cu_batch,b.proCode,b.proName,b.spec,zy.number zyNumber,vendorName,zy.slNum ");
                sb.Append("from pi_ProductsOccupation_list zy inner join V_BarCode_Info b on zy.barCode=b.barCode ");
                sb.Append(" and zy.plCode='" + plCode + "' and zy.gxCode='" + gxCode + "' and zy.isdel=0 ");
                var zyTable = cmd.GetDataTable(sb.ToString());

                sb.Clear();
                sb.Append("select l.proCode,p.proName,l.batch,sum(convert(decimal(18,2),number)) number,p.spec ");
                sb.Append("from PI_PlanMaterial_list l inner join fun_Inventory_Info p on l.proCode=p.proCode where ");
                sb.Append("plCode='" + plCode + "' and gxCode='" + gxCode + "' group by l.proCode,p.proName,l.batch,p.spec");
                var gxmTable = cmd.GetDataTable(sb.ToString());

                sb.Clear();
                sb.Append("select byCode from V_fun_BanYangInfo where isdel=0 and byBarCode in(");
                sb.Append("select materialCode from  bom_ProductionBom_sub where isdel=0 and materialType='bangun'");
                sb.Append(" and bomCode in(select bomCode from pi_ProductionPlan_info where plCode='" + plCode + "'))");
                var ysbTable = cmd.GetDataTable(sb.ToString());
                #region 获取模板

                string path = Directory.GetCurrentDirectory() + "/wwwroot/Files";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);//根据路径创建指定文件
                }

                // 原始Excel文件路径(模板)
                string originalFilePath = "";
                if (gxCode == "YS")
                {
                    originalFilePath = path + "/YSTem.xlsx";
                }
                else if (gxCode == "WRJFH")
                {
                    originalFilePath = path + "/WRJFHTem.xlsx";
                }
                else if (gxCode == "FH" || gxCode == "GSFH")
                {
                    originalFilePath = path + "/GSFHTem.xlsx";
                }
                else if (gxCode.Contains("FQ"))
                {
                    originalFilePath = path + "/CPFQTem.xlsx";
                }
                else if (gxCode.Contains("ZD"))
                {
                    originalFilePath = path + "/ZDTem.xlsx";
                }

                if (!File.Exists(originalFilePath))
                {// 检查原始文件是否存在
                    return ms;
                }

                #endregion

                newFileName = plCode + "-" + gxCode + "-" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx";
                string oldValue = "";

                
                using (var workbook = new XLWorkbook(originalFilePath))
                {// 使用ClosedXML打开原始Excel文件
                 // 遍历原始工作簿中的所有工作表
                    var borderStyle = this.ExcelTdStyle(workbook);
                    foreach (var worksheet in workbook.Worksheets)
                    {
                        #region 赋值

                        #region 计划信息  
                        worksheet.Cell(2, 2).Value = table.Rows[0]["plCode"].ToString();  //计划编码
                        if (gxCode == "YS")
                        {
                            worksheet.Cell(3, 2).Value = table.Rows[0]["cuName"].ToString();  //客户名称
                            worksheet.Cell(3, 7).Value = table.Rows[0]["proName"].ToString();  //产品名称
                            worksheet.Cell(4, 2).Value = table.Rows[0]["caizhi"].ToString();  //材质
                            worksheet.Cell(4,7).Value = table.Rows[0]["spec"].ToString();  //成品规格
                            worksheet.Cell(5, 10).Value = table.Rows[0]["number"].ToString();  //计划数量
                        }
                        else if (gxCode == "WRJFH")
                        {
                            worksheet.Cell(2, 6).Value = System.DateTime.Parse(table.Rows[0]["hDate"].ToString()).ToString("yyyy-MM-dd");
                            worksheet.Cell(3, 2).Value = table.Rows[0]["cuName"].ToString();  //客户名称
                            worksheet.Cell(3, 6).Value = table.Rows[0]["number"].ToString();  //计划数量
                            worksheet.Cell(4, 2).Value = table.Rows[0]["proName"].ToString();  //产品名称
                            worksheet.Cell(4, 6).Value = table.Rows[0]["spec"].ToString();  //成品规格
                            worksheet.Cell(5, 2).Value = table.Rows[0]["caizhi"].ToString();  //材质
                            worksheet.Cell(10, 2).Value = table.Rows[0]["memo"].ToString();  //计划备注
                        }
                        else if (gxCode.Contains("FQ"))
                        {
                            worksheet.Cell(2, 7).Value = table.Rows[0]["finishDate"].ToString();  //完工日期
                            worksheet.Cell(3, 2).Value = table.Rows[0]["cuName"].ToString();  //客户名称
                            worksheet.Cell(3, 5).Value = table.Rows[0]["proName"].ToString();  //产品名称
                            worksheet.Cell(3, 8).Value = table.Rows[0]["number"].ToString();  //计划数量
                            worksheet.Cell(4, 2).Value = table.Rows[0]["caizhi"].ToString();  //材质
                            worksheet.Cell(4, 8).Value = table.Rows[0]["spec"].ToString();  //成品规格
                            worksheet.Cell(7, 2).Value = table.Rows[0]["memo"].ToString();  //计划备注
                        }
                        else if (gxCode.Contains("ZD"))
                        {
                            worksheet.Cell(2, 6).Value = table.Rows[0]["finishDate"].ToString();  //完工日期
                            worksheet.Cell(3, 2).Value = table.Rows[0]["cuName"].ToString();  //客户名称
                            worksheet.Cell(4, 2).Value = table.Rows[0]["proName"].ToString();  //产品名称
                            worksheet.Cell(4, 6).Value = table.Rows[0]["number"].ToString();  //计划数量
                            worksheet.Cell(5, 2).Value = table.Rows[0]["spec"].ToString();  //成品规格
                            worksheet.Cell(9, 2).Value = table.Rows[0]["memo"].ToString();  //计划备注
                            worksheet.Cell(13, 6).Value = table.Rows[0]["caizhi"].ToString();  //材质

                            #region
                            for (int i = 0; i < zyTable.Rows.Count; i++)
                            {
                                worksheet.Cell(29+i, 1).Value = zyTable.Rows[i]["proCode"].ToString();
                                worksheet.Range("B"+(i+29)+":C"+ (i + 29)).Merge();
                                worksheet.Cell(29 + i, 2).Value = zyTable.Rows[i]["proName"].ToString();
                                worksheet.Range("D" + (i + 29) + ":E" + (i + 29)).Merge();
                                worksheet.Cell(29 + i, 4).Value = zyTable.Rows[i]["cu_batch"].ToString();
                                worksheet.Range("F" + (i + 29) + ":G" + (i + 29)).Merge();
                                worksheet.Cell(29 + i, 6).Value = zyTable.Rows[i]["number"].ToString();
                            }
                            var range = worksheet.Range("A28:G"+(28+ zyTable.Rows.Count));
                       
                            range.Style.Border = borderStyle;
                            #endregion
                        }


                        #endregion


                        if (gxTable.Rows.Count > 0 && int.Parse(gxTable.Rows[0]["isFinish"].ToString())==1)
                        {
                            int row_num =0,clo_num=0;
                            if (gxCode == "YS")
                            {
                                row_num = 28;
                                clo_num = 2;
                            }
                            else if (gxCode == "WRJFH")
                            {
                                row_num = 16;
                                clo_num = 2;
                            }
                            if (row_num >1)
                            {
                                worksheet.Cell(row_num, clo_num).Value = gxTable.Rows[0]["finishTime"].ToString();
                            }
                         
                        }

                        #region 工艺信息
                        foreach (DataRow dr in table.Rows)
                        {
                            oldValue = "$" + dr["fieldCode"].ToString();
                            foreach (var cell in worksheet.CellsUsed())
                            { // 如果单元格的值与旧值匹配
                                if (cell.Value.ToString() == oldValue)
                                {  // 替换为新值
                                    cell.Value = dr["fieldValue"].ToString();
                                    break;
                                }
                            }
                        }
                        //worksheet.Cell(2, 7).Value =System.DateTime.Parse(table.Rows[0]["hDate"].ToString()).ToString("yyyy-MM-dd");
                        #endregion

                        if (gxCode == "YS")
                        {

                            string byInfos = "";
                            foreach (DataRow r in ysbTable.Rows)
                            {
                                byInfos += r["byCode"].ToString() + ",";
                            }
                            foreach (var cell in worksheet.CellsUsed())
                            {
                                if (cell.Value.ToString() == "$byInfo")
                                {
                                    cell.Value = byInfos.TrimEnd(',');
                                    cell.Style.Alignment.WrapText = true;
                                    break;
                                }
                            }
                        }


               
                        if (gxCode == "YS")
                        {
                            int  btm_row = 30;
                            #region 计划占料
                            if (btm_row > 0)
                            {
                                for (int i = 0; i < zyTable.Rows.Count; i++)
                                {
                                    var range = worksheet.Range(worksheet.Cell(btm_row + i, 1), worksheet.Cell(btm_row + i, 3));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 1).Value = zyTable.Rows[i]["proName"].ToString();
                                    range = worksheet.Range(worksheet.Cell(btm_row + i, 4), worksheet.Cell(btm_row + i, 5));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 4).Value = zyTable.Rows[i]["spec"].ToString();
                                    range = worksheet.Range(worksheet.Cell(btm_row + i, 6), worksheet.Cell(btm_row + i, 7));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 6).Value = zyTable.Rows[i]["cu_batch"].ToString();
                                    range = worksheet.Range(worksheet.Cell(btm_row + i, 8), worksheet.Cell(btm_row + i, 9));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 8).Value = zyTable.Rows[i]["zyNumber"].ToString();
                                    range = worksheet.Range(worksheet.Cell(btm_row + i, 10), worksheet.Cell(btm_row + i, 11));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 10).Value = zyTable.Rows[i]["slNum"].ToString();
                                }
                            }
                            #endregion

                            #region 计划用料
                            if (gxmTable.Rows.Count > 0)
                            {
                                btm_row = btm_row + zyTable.Rows.Count;
                                var gz_range = worksheet.Range(worksheet.Cell(btm_row, 1), worksheet.Cell(btm_row, 3));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 4), worksheet.Cell(btm_row, 7));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 8), worksheet.Cell(btm_row, 9));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 10), worksheet.Cell(btm_row, 11));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();

                                ContentCenter(worksheet, btm_row, 1);
                                ContentCenter(worksheet, btm_row, 4);
                                ContentCenter(worksheet, btm_row, 8);
                                ContentCenter(worksheet, btm_row, 10);
                                worksheet.Cell(btm_row, 1).Value = "原材料编码";
                                worksheet.Cell(btm_row, 4).Value = "原材料名称";
                                worksheet.Cell(btm_row, 8).Value = "批次";
                                worksheet.Cell(btm_row, 10).Value = "数量";
                                btm_row++;
                                for (int x = 0; x < gxmTable.Rows.Count; x++)
                                {
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 1), worksheet.Cell(btm_row + x, 3));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 4), worksheet.Cell(btm_row + x, 7));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 8), worksheet.Cell(btm_row + x, 9));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 10), worksheet.Cell(btm_row + x, 11));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();

                                    worksheet.Cell(btm_row + x, 1).Value = gxmTable.Rows[x]["proCode"].ToString();
                                    worksheet.Cell(btm_row + x, 4).Value = gxmTable.Rows[x]["proName"].ToString();
                                    worksheet.Cell(btm_row + x, 8).Value = gxmTable.Rows[x]["batch"].ToString();
                                    worksheet.Cell(btm_row + x, 10).Value = gxmTable.Rows[x]["number"].ToString();
                                }
                            }
                            #endregion

                            #endregion
                        }
                        else if (gxCode == "WRJFH")
                        {
                            int btm_row = 18;

                            #region 计划占料
                            if (btm_row > 0)
                            {
                                for (int i = 0; i < zyTable.Rows.Count; i++)
                                {
                                    var range = worksheet.Range(worksheet.Cell(btm_row + i, 1), worksheet.Cell(btm_row + i, 2));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 1).Value = zyTable.Rows[i]["proName"].ToString();
                                    range = worksheet.Range(worksheet.Cell(btm_row + i, 3), worksheet.Cell(btm_row + i, 4));
                                    range.Style.Border = borderStyle;
                                    range.Merge();
                                    worksheet.Cell(btm_row + i, 3).Value = zyTable.Rows[i]["spec"].ToString();

                                    worksheet.Cell(btm_row + i, 5).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;// 设置字体居中对齐
                                    worksheet.Cell(btm_row + i, 5).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; // 可选，如果需要垂直居中
                                    worksheet.Cell(btm_row + i, 5).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 5).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 5).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 5).Style.Border.RightBorder = XLBorderStyleValues.Thin;


                                    double zyNum = double.Parse(zyTable.Rows[i]["zyNumber"].ToString());
                                    worksheet.Cell(btm_row + i, 5).Value =Math.Round(zyNum,2);

                                    worksheet.Cell(btm_row + i,6).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;// 设置字体居中对齐
                                    worksheet.Cell(btm_row + i,6).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center; // 可选，如果需要垂直居中
                                    worksheet.Cell(btm_row + i, 6).Style.Border.TopBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 6).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 6).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 6).Style.Border.RightBorder = XLBorderStyleValues.Thin;
                                    worksheet.Cell(btm_row + i, 6).Value = zyTable.Rows[i]["slNum"].ToString();
                                }
                            }
                            #endregion

                            #region 计划用料
                            if (gxmTable.Rows.Count > 0)
                            {
                                btm_row = btm_row + zyTable.Rows.Count;
                                var gz_range = worksheet.Range(worksheet.Cell(btm_row, 1), worksheet.Cell(btm_row, 2));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 3), worksheet.Cell(btm_row,4));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 5), worksheet.Cell(btm_row,5));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();
                                gz_range = worksheet.Range(worksheet.Cell(btm_row, 6), worksheet.Cell(btm_row, 6));
                                gz_range.Style.Border = borderStyle;
                                gz_range.Merge();

                                ContentCenter(worksheet, btm_row, 1);
                                ContentCenter(worksheet, btm_row, 3);
                                ContentCenter(worksheet, btm_row, 5);
                                ContentCenter(worksheet, btm_row, 6);
                                worksheet.Cell(btm_row, 1).Value = "原材料编码";
                                worksheet.Cell(btm_row, 3).Value = "原材料名称";
                                worksheet.Cell(btm_row, 5).Value = "批次";
                                worksheet.Cell(btm_row, 6).Value = "数量";
                                btm_row++;
                                for (int x = 0; x < gxmTable.Rows.Count; x++)
                                {
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 1), worksheet.Cell(btm_row + x, 2));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 3), worksheet.Cell(btm_row + x,4));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 5), worksheet.Cell(btm_row + x, 5));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();
                                    gz_range = worksheet.Range(worksheet.Cell(btm_row + x, 6), worksheet.Cell(btm_row + x, 6));
                                    gz_range.Style.Border = borderStyle;
                                    gz_range.Merge();

                                    worksheet.Cell(btm_row + x, 1).Value = gxmTable.Rows[x]["proCode"].ToString();
                                    worksheet.Cell(btm_row + x, 3).Value = gxmTable.Rows[x]["proName"].ToString();
                                    worksheet.Cell(btm_row + x, 5).Value = gxmTable.Rows[x]["batch"].ToString();
                                    worksheet.Cell(btm_row + x, 6).Value = gxmTable.Rows[x]["number"].ToString();
                                }
                            }
                            #endregion

                        }



                        #region 将没有填写的工艺字段赋空值
                        foreach (var cell in worksheet.CellsUsed())
                        {
                            // 如果单元格的值与旧值匹配
                            if (cell.Value.ToString().Contains("$"))
                            {// 替换为新值
                                cell.Value = "";
                            }
                        }
                        #endregion

                     

                   
                    }
                    ms = new System.IO.MemoryStream();
                    workbook.SaveAs(ms);
                    // 重置 MemoryStream 的位置到起始点
                    ms.Position = 0;

                    // 设置 HTTP 响应头
                    var contentDisposition = new ContentDisposition
                    {
                        FileName = newFileName,
                        Inline = false, // 表示这是一个附件，而不是内联显示的内容
                    };
                   

                }

            }
            catch (Exception ex)
            {
                
            }

            return ms;
        }
        /// <summary>
        /// excel单元格样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        private IXLBorder ExcelTdStyle(XLWorkbook workbook)
        {
            var borderStyle = workbook.Style.Border;
            borderStyle.TopBorder = XLBorderStyleValues.Thin;
            borderStyle.BottomBorder = XLBorderStyleValues.Thin;
            borderStyle.LeftBorder = XLBorderStyleValues.Thin;
            borderStyle.RightBorder = XLBorderStyleValues.Thin;
            return borderStyle;
        }
        private void ContentCenter(IXLWorksheet worksheet,int roNum,int cloNum)
        {
            var cell = worksheet.Cell(roNum, cloNum);
            var cellStyle = cell.Style;
            cellStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;// 设置字体居中对齐
            cellStyle.Alignment.Vertical = XLAlignmentVerticalValues.Center; // 可选，如果需要垂直居中也可以设置
            cell.Style = cellStyle;  // 应用样式到单元格
        }
    }
}
